diff --git a/portal-impl/src/com/liferay/portal/bean/RendererImpl.java b/portal-impl/src/com/liferay/portal/bean/RendererImpl.java index f2409a08cf3503..7eeb4ec48bf3cc 100644 --- a/portal-impl/src/com/liferay/portal/bean/RendererImpl.java +++ b/portal-impl/src/com/liferay/portal/bean/RendererImpl.java @@ -1,417 +1,415 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portal.bean; - -import com.liferay.portal.kernel.bean.BeanLocator; -import com.liferay.portal.kernel.bean.BeanLocatorException; -import com.liferay.portal.kernel.bean.PortalBeanLocatorUtil; -import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil; -import com.liferay.portal.kernel.bean.Renderer; -import com.liferay.portal.kernel.bean.RendererException; -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.util.ParamUtil; -import com.liferay.portal.kernel.util.PropsUtil; -import com.liferay.portal.kernel.util.StringPool; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.kernel.velocity.VelocityContext; -import com.liferay.portal.kernel.velocity.VelocityEngineUtil; -import com.liferay.portal.kernel.velocity.VelocityVariablesUtil; -import com.liferay.portal.util.PortalUtil; -import com.liferay.portal.util.PrefsPropsUtil; -import com.liferay.portlet.PortletPreferencesFactoryUtil; -import com.liferay.util.ContentUtil; - -import java.lang.reflect.Method; - -import javax.portlet.PortletPreferences; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Raymond Augé - */ -public class RendererImpl implements Renderer { - - public String renderBean( - HttpServletRequest request, HttpServletResponse response, - Object bean) - throws RendererException { - - return renderBean(request, response, null, bean, null); - } - - public String renderBean( - HttpServletRequest request, HttpServletResponse response, - Object bean, String varientSuffix) - throws RendererException { - - return renderBean(request, response, null, bean, varientSuffix); - } - - public String renderBean( - HttpServletRequest request, HttpServletResponse response, - String servletContextName, Object bean) - throws RendererException { - - return renderBean(request, response, servletContextName, bean, null); - } - - public String renderBean( - HttpServletRequest request, HttpServletResponse response, - String servletContextName, Object bean, String varientSuffix) - throws RendererException { - - if (bean == null) { - return null; - } - - long companyId = PortalUtil.getCompanyId(request); - - String className = normalizeClassName(bean.getClass().getName()); - - if (Validator.isNotNull(varientSuffix)) { - className = varientSuffix; - } - - String velocityTemplateContent = null; - - PortletPreferences preferences = getPortletPreferences(request); - - if (preferences != null) { - velocityTemplateContent = preferences.getValue( - RENDERER_TEMPLATE_PREFIX + className, StringPool.BLANK); - } - - if (Validator.isNull(velocityTemplateContent) && - Validator.isNotNull(servletContextName)) { - - if (servletContextName.startsWith(StringPool.SLASH)) { - servletContextName = servletContextName.substring(1); - } - - try { - BeanLocator beanLocator = PortletBeanLocatorUtil.getBeanLocator( - servletContextName); - - velocityTemplateContent = ContentUtil.get( - beanLocator.getClassLoader(), - PropsUtil.get(RENDERER_TEMPLATE_PREFIX + className)); - } - catch (Exception e) { - } - } - - if (Validator.isNull(velocityTemplateContent)) { - try { - velocityTemplateContent = PrefsPropsUtil.getContent( - companyId, RENDERER_TEMPLATE_PREFIX + className); - } - catch (Exception e) { - } - } - - if (Validator.isNull(velocityTemplateContent)) { - _log.warn("No entity renderer template found for " + className); - - return null; - } - - VelocityContext velocityContext = - VelocityEngineUtil.getWrappedStandardToolsContext(); - - // Velocity variables - - try { - VelocityVariablesUtil.insertVariables(velocityContext, request); - } - catch (Exception e) { - throw new RendererException(e); - } - - velocityContext.put(_BEAN, bean); - - try { - UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter(); - - VelocityEngineUtil.mergeTemplate( - className, velocityTemplateContent, velocityContext, - unsyncStringWriter); - - return unsyncStringWriter.toString(); - } - catch (Exception e) { - _log.error(e, e); - - throw new RendererException(e); - } - } - - public String renderBean( - PortletRequest portletRequest, PortletResponse portletResponse, - Object bean) - throws RendererException { - - return renderBean(portletRequest, portletResponse, null, bean, null); - } - - public String renderBean( - PortletRequest portletRequest, PortletResponse portletResponse, - Object bean, String varientSuffix) - throws RendererException { - - return renderBean( - portletRequest, portletResponse, null, bean, varientSuffix); - } - - public String renderBean( - PortletRequest portletRequest, PortletResponse portletResponse, - String servletContextName, Object bean) - throws RendererException { - - return renderBean( - portletRequest, portletResponse, servletContextName, bean, null); - } - - public String renderBean( - PortletRequest portletRequest, PortletResponse portletResponse, - String servletContextName, Object bean, String varientSuffix) - throws RendererException { - - HttpServletRequest request = PortalUtil.getHttpServletRequest( - portletRequest); - HttpServletResponse response = PortalUtil.getHttpServletResponse( - portletResponse); - - return renderBean( - request, response, servletContextName, bean, varientSuffix); - } - - public String renderEntity( - HttpServletRequest request, HttpServletResponse response, - String className, Object classPK) - throws RendererException { - - return renderEntity(request, response, null, className, classPK, null); - } - - public String renderEntity( - HttpServletRequest request, HttpServletResponse response, - String className, Object classPK, String varientSuffix) - throws RendererException { - - return renderEntity( - request, response, null, className, classPK, varientSuffix); - } - - public String renderEntity( - HttpServletRequest request, HttpServletResponse response, - String servletContextName, String className, Object classPK) - throws RendererException { - - return renderEntity( - request, response, servletContextName, className, classPK, null); - } - - public String renderEntity( - HttpServletRequest request, HttpServletResponse response, - String servletContextName, String className, Object classPK, - String varientSuffix) - throws RendererException { - - if (Validator.isNull(className)) { - return null; - } - - className = normalizeClassName(className); - - String[] beanNameParts = StringUtil.split(className, _MODEL); - - Object serviceBean = null; - - if (Validator.isNotNull(servletContextName)) { - if (servletContextName.startsWith(StringPool.SLASH)) { - servletContextName = servletContextName.substring(1); - } - - try { - serviceBean = PortletBeanLocatorUtil.locate( - servletContextName, - beanNameParts[0] + _SERVICE + beanNameParts[1] + - _LOCAL_SERVICE_UTIL); - } - catch (BeanLocatorException ble) { - } - } - else { - try { - serviceBean = PortalBeanLocatorUtil.locate( - beanNameParts[0] + _SERVICE + beanNameParts[1] + - _LOCAL_SERVICE_UTIL); - } - catch (BeanLocatorException ble) { - } - } - - Object bean = null; - - if (serviceBean != null) { - Method getMethod = null; - - try { - getMethod = serviceBean.getClass().getDeclaredMethod( - "get" + beanNameParts[1], classPK.getClass()); - } - catch (Exception e) { - } - - if (getMethod == null) { - try { - getMethod = serviceBean.getClass().getDeclaredMethod( - "get" + beanNameParts[1], - mapToPrimitive(classPK.getClass())); - } - catch (Exception e) { - } - } - - if (getMethod != null) { - try { - bean = getMethod.invoke(null, classPK); - } - catch (Exception e) { - _log.warn(e.getMessage()); - } - } - } - - return renderBean( - request, response, servletContextName, bean, varientSuffix); - } - - public String renderEntity( - PortletRequest portletRequest, PortletResponse portletResponse, - String className, Object classPK) - throws RendererException { - - return renderEntity( - portletRequest, portletResponse, null, className, classPK, null); - } - - public String renderEntity( - PortletRequest portletRequest, PortletResponse portletResponse, - String className, Object classPK, String varientSuffix) - throws RendererException { - - return renderEntity( - portletRequest, portletResponse, null, className, classPK, - varientSuffix); - } - - public String renderEntity( - PortletRequest portletRequest, PortletResponse portletResponse, - String servletContextName, String className, Object classPK) - throws RendererException { - - return renderEntity( - portletRequest, portletResponse, servletContextName, className, - classPK, null); - } - - public String renderEntity( - PortletRequest portletRequest, PortletResponse portletResponse, - String servletContextName, String className, Object classPK, - String varientSuffix) - throws RendererException { - - HttpServletRequest request = PortalUtil.getHttpServletRequest( - portletRequest); - HttpServletResponse response = PortalUtil.getHttpServletResponse( - portletResponse); - - return renderEntity( - request, response, servletContextName, className, classPK, - varientSuffix); - } - - protected PortletPreferences getPortletPreferences( - HttpServletRequest request) { - - PortletPreferences preferences = PortalUtil.getPreferences(request); - - String portletResource = ParamUtil.getString( - request, "portletResource"); - - if (Validator.isNotNull(portletResource)) { - try { - preferences = PortletPreferencesFactoryUtil.getPortletSetup( - request, portletResource); - } - catch (PortalException pe) { - } - catch (SystemException se) { - } - } - - return preferences; - } - - protected Class mapToPrimitive(Class clazz) { - Class mapping = clazz; - - if (clazz == Integer.class) { - mapping = int.class; - } - else if (clazz == Long.class) { - mapping = long.class; - } - - return mapping; - } - - protected String normalizeClassName(String className) { - className = StringUtil.replace( - className, - new String[] { - ".impl.", - "Impl" - }, - new String[] { - StringPool.PERIOD, - StringPool.BLANK - } - ); - - return className; - } - - private static final String _BEAN = "bean"; - - private static final String _LOCAL_SERVICE_UTIL = "LocalServiceUtil"; - - private static final String _MODEL = ".model."; - - private static final String _SERVICE = ".service."; - - private static Log _log = LogFactoryUtil.getLog(RendererImpl.class); - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portal.bean; + +import com.liferay.portal.kernel.bean.BeanLocator; +import com.liferay.portal.kernel.bean.BeanLocatorException; +import com.liferay.portal.kernel.bean.PortalBeanLocatorUtil; +import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil; +import com.liferay.portal.kernel.bean.Renderer; +import com.liferay.portal.kernel.bean.RendererException; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.util.ParamUtil; +import com.liferay.portal.kernel.util.PropsUtil; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.kernel.velocity.VelocityContext; +import com.liferay.portal.kernel.velocity.VelocityEngineUtil; +import com.liferay.portal.kernel.velocity.VelocityVariablesUtil; +import com.liferay.portal.util.PortalUtil; +import com.liferay.portal.util.PrefsPropsUtil; +import com.liferay.portlet.PortletPreferencesFactoryUtil; +import com.liferay.util.ContentUtil; + +import java.lang.reflect.Method; + +import javax.portlet.PortletPreferences; +import javax.portlet.PortletRequest; +import javax.portlet.PortletResponse; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author Raymond Augé + */ +public class RendererImpl implements Renderer { + + public String renderBean( + HttpServletRequest request, HttpServletResponse response, + Object bean) + throws RendererException { + + return renderBean(request, response, null, bean, null); + } + + public String renderBean( + HttpServletRequest request, HttpServletResponse response, + Object bean, String varientSuffix) + throws RendererException { + + return renderBean(request, response, null, bean, varientSuffix); + } + + public String renderBean( + HttpServletRequest request, HttpServletResponse response, + String servletContextName, Object bean) + throws RendererException { + + return renderBean(request, response, servletContextName, bean, null); + } + + public String renderBean( + HttpServletRequest request, HttpServletResponse response, + String servletContextName, Object bean, String varientSuffix) + throws RendererException { + + if (bean == null) { + return null; + } + + long companyId = PortalUtil.getCompanyId(request); + + String className = normalizeClassName(bean.getClass().getName()); + + if (Validator.isNotNull(varientSuffix)) { + className = varientSuffix; + } + + String velocityTemplateContent = null; + + PortletPreferences preferences = getPortletPreferences(request); + + if (preferences != null) { + velocityTemplateContent = preferences.getValue( + RENDERER_TEMPLATE_PREFIX + className, StringPool.BLANK); + } + + if (Validator.isNull(velocityTemplateContent) && + Validator.isNotNull(servletContextName)) { + + if (servletContextName.startsWith(StringPool.SLASH)) { + servletContextName = servletContextName.substring(1); + } + + try { + BeanLocator beanLocator = PortletBeanLocatorUtil.getBeanLocator( + servletContextName); + + velocityTemplateContent = ContentUtil.get( + beanLocator.getClassLoader(), + PropsUtil.get(RENDERER_TEMPLATE_PREFIX + className)); + } + catch (Exception e) { + } + } + + if (Validator.isNull(velocityTemplateContent)) { + try { + velocityTemplateContent = PrefsPropsUtil.getContent( + companyId, RENDERER_TEMPLATE_PREFIX + className); + } + catch (Exception e) { + } + } + + if (Validator.isNull(velocityTemplateContent)) { + _log.warn("No entity renderer template found for " + className); + + return null; + } + + VelocityContext velocityContext = + VelocityEngineUtil.getWrappedStandardToolsContext(); + + // Velocity variables + + try { + VelocityVariablesUtil.insertVariables(velocityContext, request); + } + catch (Exception e) { + throw new RendererException(e); + } + + velocityContext.put(_BEAN, bean); + + try { + UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter(); + + VelocityEngineUtil.mergeTemplate( + className, velocityTemplateContent, velocityContext, + unsyncStringWriter); + + return unsyncStringWriter.toString(); + } + catch (Exception e) { + _log.error(e, e); + + throw new RendererException(e); + } + } + + public String renderBean( + PortletRequest portletRequest, PortletResponse portletResponse, + Object bean) + throws RendererException { + + return renderBean(portletRequest, portletResponse, null, bean, null); + } + + public String renderBean( + PortletRequest portletRequest, PortletResponse portletResponse, + Object bean, String varientSuffix) + throws RendererException { + + return renderBean( + portletRequest, portletResponse, null, bean, varientSuffix); + } + + public String renderBean( + PortletRequest portletRequest, PortletResponse portletResponse, + String servletContextName, Object bean) + throws RendererException { + + return renderBean( + portletRequest, portletResponse, servletContextName, bean, null); + } + + public String renderBean( + PortletRequest portletRequest, PortletResponse portletResponse, + String servletContextName, Object bean, String varientSuffix) + throws RendererException { + + HttpServletRequest request = PortalUtil.getHttpServletRequest( + portletRequest); + HttpServletResponse response = PortalUtil.getHttpServletResponse( + portletResponse); + + return renderBean( + request, response, servletContextName, bean, varientSuffix); + } + + public String renderEntity( + HttpServletRequest request, HttpServletResponse response, + String className, Object classPK) + throws RendererException { + + return renderEntity(request, response, null, className, classPK, null); + } + + public String renderEntity( + HttpServletRequest request, HttpServletResponse response, + String className, Object classPK, String varientSuffix) + throws RendererException { + + return renderEntity( + request, response, null, className, classPK, varientSuffix); + } + + public String renderEntity( + HttpServletRequest request, HttpServletResponse response, + String servletContextName, String className, Object classPK) + throws RendererException { + + return renderEntity( + request, response, servletContextName, className, classPK, null); + } + + public String renderEntity( + HttpServletRequest request, HttpServletResponse response, + String servletContextName, String className, Object classPK, + String varientSuffix) + throws RendererException { + + if (Validator.isNull(className)) { + return null; + } + + className = normalizeClassName(className); + + String[] beanNameParts = StringUtil.split(className, _MODEL); + + Object serviceBean = null; + + if (Validator.isNotNull(servletContextName)) { + if (servletContextName.startsWith(StringPool.SLASH)) { + servletContextName = servletContextName.substring(1); + } + + try { + serviceBean = PortletBeanLocatorUtil.locate( + servletContextName, + beanNameParts[0] + _SERVICE + beanNameParts[1] + + _LOCAL_SERVICE_UTIL); + } + catch (BeanLocatorException ble) { + } + } + else { + try { + serviceBean = PortalBeanLocatorUtil.locate( + beanNameParts[0] + _SERVICE + beanNameParts[1] + + _LOCAL_SERVICE_UTIL); + } + catch (BeanLocatorException ble) { + } + } + + Object bean = null; + + if (serviceBean != null) { + Method getMethod = null; + + try { + getMethod = serviceBean.getClass().getDeclaredMethod( + "get" + beanNameParts[1], classPK.getClass()); + } + catch (Exception e) { + } + + if (getMethod == null) { + try { + getMethod = serviceBean.getClass().getDeclaredMethod( + "get" + beanNameParts[1], + mapToPrimitive(classPK.getClass())); + } + catch (Exception e) { + } + } + + if (getMethod != null) { + try { + bean = getMethod.invoke(null, classPK); + } + catch (Exception e) { + _log.warn(e.getMessage()); + } + } + } + + return renderBean( + request, response, servletContextName, bean, varientSuffix); + } + + public String renderEntity( + PortletRequest portletRequest, PortletResponse portletResponse, + String className, Object classPK) + throws RendererException { + + return renderEntity( + portletRequest, portletResponse, null, className, classPK, null); + } + + public String renderEntity( + PortletRequest portletRequest, PortletResponse portletResponse, + String className, Object classPK, String varientSuffix) + throws RendererException { + + return renderEntity( + portletRequest, portletResponse, null, className, classPK, + varientSuffix); + } + + public String renderEntity( + PortletRequest portletRequest, PortletResponse portletResponse, + String servletContextName, String className, Object classPK) + throws RendererException { + + return renderEntity( + portletRequest, portletResponse, servletContextName, className, + classPK, null); + } + + public String renderEntity( + PortletRequest portletRequest, PortletResponse portletResponse, + String servletContextName, String className, Object classPK, + String varientSuffix) + throws RendererException { + + HttpServletRequest request = PortalUtil.getHttpServletRequest( + portletRequest); + HttpServletResponse response = PortalUtil.getHttpServletResponse( + portletResponse); + + return renderEntity( + request, response, servletContextName, className, classPK, + varientSuffix); + } + + protected PortletPreferences getPortletPreferences( + HttpServletRequest request) { + + PortletPreferences preferences = PortalUtil.getPreferences(request); + + String portletResource = ParamUtil.getString( + request, "portletResource"); + + if (Validator.isNotNull(portletResource)) { + try { + preferences = PortletPreferencesFactoryUtil.getPortletSetup( + request, portletResource); + } + catch (PortalException pe) { + } + catch (SystemException se) { + } + } + + return preferences; + } + + protected Class mapToPrimitive(Class clazz) { + Class mapping = clazz; + + if (clazz == Integer.class) { + mapping = int.class; + } + else if (clazz == Long.class) { + mapping = long.class; + } + + return mapping; + } + + protected String normalizeClassName(String className) { + className = StringUtil.replace( + className, + new String[] { + ".impl.", "Impl" + }, + new String[] { + StringPool.PERIOD, StringPool.BLANK + } + ); + + return className; + } + + private static final String _BEAN = "bean"; + + private static final String _LOCAL_SERVICE_UTIL = "LocalServiceUtil"; + + private static final String _MODEL = ".model."; + + private static final String _SERVICE = ".service."; + + private static Log _log = LogFactoryUtil.getLog(RendererImpl.class); + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portal/cache/ehcache/EhcacheConfigurationUtil.java b/portal-impl/src/com/liferay/portal/cache/ehcache/EhcacheConfigurationUtil.java index 9e5b487ca9b2b5..b279aa6eee1bfd 100644 --- a/portal-impl/src/com/liferay/portal/cache/ehcache/EhcacheConfigurationUtil.java +++ b/portal-impl/src/com/liferay/portal/cache/ehcache/EhcacheConfigurationUtil.java @@ -45,8 +45,7 @@ public static Configuration getConfiguration( } public static Configuration getConfiguration( - String configurationPath, boolean clusterAware, - boolean usingDefault) { + String configurationPath, boolean clusterAware, boolean usingDefault) { if (Validator.isNull(configurationPath)) { return null; diff --git a/portal-impl/src/com/liferay/portal/dao/db/BaseDB.java b/portal-impl/src/com/liferay/portal/dao/db/BaseDB.java index 9e5d7732c9feb9..c6cb26aefd46b7 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/BaseDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/BaseDB.java @@ -962,12 +962,9 @@ protected String replaceTemplate(String template, String[] actual) { }; protected static final String[] TEMPLATE = { - "##", "TRUE", "FALSE", - "'01/01/1970'", "CURRENT_TIMESTAMP", - " BLOB", " SBLOB", " BOOLEAN", " DATE", - " DOUBLE", " INTEGER", " LONG", - " STRING", " TEXT", " VARCHAR", - " IDENTITY", "COMMIT_TRANSACTION" + "##", "TRUE", "FALSE", "'01/01/1970'", "CURRENT_TIMESTAMP", " BLOB", + " SBLOB", " BOOLEAN", " DATE", " DOUBLE", " INTEGER", " LONG", + " STRING", " TEXT", " VARCHAR", " IDENTITY", "COMMIT_TRANSACTION" }; private static final boolean _SUPPORTS_ALTER_COLUMN_NAME = true; diff --git a/portal-impl/src/com/liferay/portal/dao/db/DB2DB.java b/portal-impl/src/com/liferay/portal/dao/db/DB2DB.java index 581cd4e520d236..210f6cccbc5139 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/DB2DB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/DB2DB.java @@ -215,11 +215,9 @@ private void _reorgTables(String[] templates) throws SQLException { } private static final String[] _DB2 = { - "--", "1", "0", - "'1970-01-01-00.00.00.000000'", "current timestamp", - " blob", " blob", " smallint", " timestamp", - " double", " integer", " bigint", - " varchar(500)", " clob", " varchar", + "--", "1", "0", "'1970-01-01-00.00.00.000000'", "current timestamp", + " blob", " blob", " smallint", " timestamp", " double", " integer", + " bigint", " varchar(500)", " clob", " varchar", " generated always as identity", "commit" }; diff --git a/portal-impl/src/com/liferay/portal/dao/db/DerbyDB.java b/portal-impl/src/com/liferay/portal/dao/db/DerbyDB.java index 133679ee470817..eb7e8dc3d26e7a 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/DerbyDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/DerbyDB.java @@ -139,11 +139,9 @@ else if (line.indexOf(DROP_INDEX) != -1) { } private static final String[] _DERBY = { - "--", "1", "0", - "'1970-01-01-00.00.00.000000'", "current timestamp", - " blob", " blob", " smallint", " timestamp", - " double", " integer", " bigint", - " varchar(4000)", " clob", " varchar", + "--", "1", "0", "'1970-01-01-00.00.00.000000'", "current timestamp", + " blob", " blob", " smallint", " timestamp", " double", " integer", + " bigint", " varchar(4000)", " clob", " varchar", " generated always as identity", "commit" }; diff --git a/portal-impl/src/com/liferay/portal/dao/db/FirebirdDB.java b/portal-impl/src/com/liferay/portal/dao/db/FirebirdDB.java index 7073334f77fa19..cc0547bc31a1e3 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/FirebirdDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/FirebirdDB.java @@ -130,12 +130,9 @@ else if (line.indexOf(DROP_INDEX) != -1) { } private static final String[] _FIREBIRD = { - "--", "1", "0", - "'01/01/1970'", "current_timestamp", - " blob", " blob", " smallint", " timestamp", - " double precision", " integer", " int64", - " varchar(4000)", " blob", " varchar", - "", "commit" + "--", "1", "0", "'01/01/1970'", "current_timestamp", " blob", " blob", + " smallint", " timestamp", " double precision", " integer", " int64", + " varchar(4000)", " blob", " varchar", "", "commit" }; private static FirebirdDB _instance = new FirebirdDB(); diff --git a/portal-impl/src/com/liferay/portal/dao/db/HypersonicDB.java b/portal-impl/src/com/liferay/portal/dao/db/HypersonicDB.java index e43fe5a4c09889..66e5b66354ea67 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/HypersonicDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/HypersonicDB.java @@ -108,12 +108,9 @@ else if (line.indexOf(DROP_INDEX) != -1) { } private static final String[] _HYPERSONIC = { - "//", "true", "false", - "'1970-01-01 00:00:00'", "now()", - " blob", " blob", " bit", " timestamp", - " double", " int", " bigint", - " longvarchar", " longvarchar", " varchar", - "", "commit" + "//", "true", "false", "'1970-01-01 00:00:00'", "now()", " blob", + " blob", " bit", " timestamp", " double", " int", " bigint", + " longvarchar", " longvarchar", " varchar", "", "commit" }; private static HypersonicDB _instance = new HypersonicDB(); diff --git a/portal-impl/src/com/liferay/portal/dao/db/InformixDB.java b/portal-impl/src/com/liferay/portal/dao/db/InformixDB.java index a59196400dfd3e..8ba00bab5c2fa8 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/InformixDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/InformixDB.java @@ -177,12 +177,9 @@ else if (line.indexOf("create table") >= 0) { } private static final String[] _INFORMIX_TEMPLATE = { - "--", "'T'", "'F'", - "'1970-01-01'", "CURRENT YEAR TO FRACTION", - " blob", " blob", " boolean", " datetime YEAR TO FRACTION", - " float", " int", " int8", - " lvarchar", " text", " varchar", - "", "commit" + "--", "'T'", "'F'", "'1970-01-01'", "CURRENT YEAR TO FRACTION", " blob", + " blob", " boolean", " datetime YEAR TO FRACTION", " float", " int", + " int8", " lvarchar", " text", " varchar", "", "commit" }; private static InformixDB _instance = new InformixDB(); diff --git a/portal-impl/src/com/liferay/portal/dao/db/IngresDB.java b/portal-impl/src/com/liferay/portal/dao/db/IngresDB.java index 33503bd64e9d4b..4575f1941a220c 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/IngresDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/IngresDB.java @@ -148,12 +148,9 @@ else if (line.indexOf(DROP_PRIMARY_KEY) != -1) { } private static final String[] _INGRES = { - "--", "1", "0", - "'1970-01-01'", "date('now')", - " blob", " blob", " tinyint", " timestamp", - " float", " integer", " bigint", - " varchar(1000)", " long varchar", " varchar", - "", "commit;\\g" + "--", "1", "0", "'1970-01-01'", "date('now')", " blob", " blob", + " tinyint", " timestamp", " float", " integer", " bigint", + " varchar(1000)", " long varchar", " varchar", "", "commit;\\g" }; private static final boolean _SUPPORTS_ALTER_COLUMN_NAME = false; diff --git a/portal-impl/src/com/liferay/portal/dao/db/JDataStoreDB.java b/portal-impl/src/com/liferay/portal/dao/db/JDataStoreDB.java index 560b1493b4041a..7e35a06a41d7d6 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/JDataStoreDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/JDataStoreDB.java @@ -59,12 +59,9 @@ protected String[] getTemplate() { } private static final String[] _JDATASTORE = { - "--", "TRUE", "FALSE", - "'1970-01-01'", "current_timestamp", - " binary", " binary", " boolean", " date", - " double", " integer", " bigint", - " long varchar", " long varchar", " varchar", - "", "commit" + "--", "TRUE", "FALSE", "'1970-01-01'", "current_timestamp", " binary", + " binary", " boolean", " date", " double", " integer", " bigint", + " long varchar", " long varchar", " varchar", "", "commit" }; private static JDataStoreDB _instance = new JDataStoreDB(); diff --git a/portal-impl/src/com/liferay/portal/dao/db/MySQLDB.java b/portal-impl/src/com/liferay/portal/dao/db/MySQLDB.java index ccca8fc531fd38..15fd653a2cabac 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/MySQLDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/MySQLDB.java @@ -199,12 +199,9 @@ else if (line.startsWith(ALTER_COLUMN_TYPE)) { } private static final String[] _MYSQL = { - "##", "1", "0", - "'1970-01-01'", "now()", - " longblob", " longblob", " tinyint", " datetime", - " double", " integer", " bigint", - " longtext", " longtext", " varchar", - " auto_increment", "commit" + "##", "1", "0", "'1970-01-01'", "now()", " longblob", " longblob", + " tinyint", " datetime", " double", " integer", " bigint", " longtext", + " longtext", " varchar", " auto_increment", "commit" }; private static final boolean _SUPPORTS_DATE_MILLISECONDS = false; diff --git a/portal-impl/src/com/liferay/portal/dao/db/OracleDB.java b/portal-impl/src/com/liferay/portal/dao/db/OracleDB.java index da963ee0a1355f..b7791455813094 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/OracleDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/OracleDB.java @@ -318,9 +318,8 @@ private String _preBuildSQL(String template) throws IOException { "--", "1", "0", "to_date('1970-01-01 00:00:00','YYYY-MM-DD HH24:MI:SS')", "sysdate", " blob", " blob", " number(1, 0)", " timestamp", - " number(30,20)", " number(30,0)", " number(30,0)", - " varchar2(4000)", " clob", " varchar2", - "", "commit" + " number(30,20)", " number(30,0)", " number(30,0)", " varchar2(4000)", + " clob", " varchar2", "", "commit" }; private static final boolean _SUPPORTS_INLINE_DISTINCT = false; diff --git a/portal-impl/src/com/liferay/portal/dao/db/PostgreSQLDB.java b/portal-impl/src/com/liferay/portal/dao/db/PostgreSQLDB.java index c051e2ec6b2d53..c62efea0d453d3 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/PostgreSQLDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/PostgreSQLDB.java @@ -193,12 +193,9 @@ else if (line.indexOf("\\\'") != -1) { } private static final String[] _POSTGRESQL = { - "--", "true", "false", - "'01/01/1970'", "current_timestamp", - " oid", " bytea", " bool", " timestamp", - " double precision", " integer", " bigint", - " text", " text", " varchar", - "", "commit" + "--", "true", "false", "'01/01/1970'", "current_timestamp", " oid", + " bytea", " bool", " timestamp", " double precision", " integer", + " bigint", " text", " text", " varchar", "", "commit" }; private static PostgreSQLDB _instance = new PostgreSQLDB(); diff --git a/portal-impl/src/com/liferay/portal/dao/db/SAPDB.java b/portal-impl/src/com/liferay/portal/dao/db/SAPDB.java index bfbc4e0a4580de..697b5d89db9bea 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/SAPDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/SAPDB.java @@ -99,12 +99,9 @@ else if (line.startsWith(ALTER_COLUMN_TYPE)) { } private static final String[] _SAP = { - "##", "TRUE", "FALSE", - "'1970-01-01 00:00:00.000000'", "timestamp", - " blob", " blob", " boolean", " timestamp", - " float", " int", " bigint", - " varchar", " varchar", " varchar", - "", "commit" + "##", "TRUE", "FALSE", "'1970-01-01 00:00:00.000000'", "timestamp", + " blob", " blob", " boolean", " timestamp", " float", " int", " bigint", + " varchar", " varchar", " varchar", "", "commit" }; private static SAPDB _instance = new SAPDB(); diff --git a/portal-impl/src/com/liferay/portal/dao/db/SQLServerDB.java b/portal-impl/src/com/liferay/portal/dao/db/SQLServerDB.java index fd9faa5f8ae8b7..563168ad235489 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/SQLServerDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/SQLServerDB.java @@ -215,11 +215,9 @@ else if (line.indexOf(DROP_INDEX) != -1) { } private static final String[] _SQL_SERVER = { - "--", "1", "0", - "'19700101'", "GetDate()", - " image", " image", " bit", " datetime", - " float", " int", " bigint", - " nvarchar(2000)", " ntext", " nvarchar", + "--", "1", "0", "'19700101'", "GetDate()", " image", " image", " bit", + " datetime", " float", " int", " bigint", " nvarchar(2000)", " ntext", + " nvarchar", " identity(1,1)", "go" }; diff --git a/portal-impl/src/com/liferay/portal/dao/db/SybaseDB.java b/portal-impl/src/com/liferay/portal/dao/db/SybaseDB.java index 1c952db6798f78..ebf9e6005af2e2 100644 --- a/portal-impl/src/com/liferay/portal/dao/db/SybaseDB.java +++ b/portal-impl/src/com/liferay/portal/dao/db/SybaseDB.java @@ -163,11 +163,9 @@ else if (line.indexOf(DROP_INDEX) != -1) { private static final boolean _SUPPORTS_INLINE_DISTINCT = false; private static final String[] _SYBASE = { - "--", "1", "0", - "'19700101'", "getdate()", - " image", " image", " int", " datetime", - " float", " int", " decimal(20,0)", - " varchar(1000)", " text", " varchar", + "--", "1", "0", "'19700101'", "getdate()", " image", " image", " int", + " datetime", " float", " int", + " decimal(20,0)", " varchar(1000)", " text", " varchar", " identity(1,1)", "go" }; diff --git a/portal-impl/src/com/liferay/portal/deploy/DeployUtil.java b/portal-impl/src/com/liferay/portal/deploy/DeployUtil.java index d54e0c73c72ba9..cd5492e9d201bc 100644 --- a/portal-impl/src/com/liferay/portal/deploy/DeployUtil.java +++ b/portal-impl/src/com/liferay/portal/deploy/DeployUtil.java @@ -184,8 +184,7 @@ public static void undeploy(String appServerType, File deployDir) } int undeployInterval = PrefsPropsUtil.getInteger( - PropsKeys.HOT_UNDEPLOY_INTERVAL, - PropsValues.HOT_UNDEPLOY_INTERVAL); + PropsKeys.HOT_UNDEPLOY_INTERVAL, PropsValues.HOT_UNDEPLOY_INTERVAL); if (_log.isInfoEnabled()) { _log.info( diff --git a/portal-impl/src/com/liferay/portal/deploy/hot/HookHotDeployListener.java b/portal-impl/src/com/liferay/portal/deploy/hot/HookHotDeployListener.java index 41528d4cf4822e..3dbc48433fb415 100644 --- a/portal-impl/src/com/liferay/portal/deploy/hot/HookHotDeployListener.java +++ b/portal-impl/src/com/liferay/portal/deploy/hot/HookHotDeployListener.java @@ -173,120 +173,71 @@ public class HookHotDeployListener extends BaseHotDeployListener implements PropsKeys { public static final String[] SUPPORTED_PROPERTIES = { - "admin.default.group.names", - "admin.default.role.names", - "admin.default.user.group.names", - "asset.publisher.display.styles", - "auth.forward.by.last.path", - "auth.public.paths", - "auto.deploy.listeners", - "application.startup.events", - "auth.failure", - "auth.max.failures", - "auth.token.impl", - "auth.pipeline.post", - "auth.pipeline.pre", - "auto.login.hooks", - "captcha.check.portal.create_account", - "captcha.engine.impl", + "admin.default.group.names", "admin.default.role.names", + "admin.default.user.group.names", "asset.publisher.display.styles", + "auth.forward.by.last.path", "auth.public.paths", + "auto.deploy.listeners", "application.startup.events", "auth.failure", + "auth.max.failures", "auth.token.impl", "auth.pipeline.post", + "auth.pipeline.pre", "auto.login.hooks", + "captcha.check.portal.create_account", "captcha.engine.impl", "company.settings.form.configuration", "company.settings.form.identification", "company.settings.form.miscellaneous", - "control.panel.entry.class.default", - "convert.processes", - "default.landing.page.path", - "dl.file.entry.drafts.enabled", - "dl.file.entry.processors", - "dl.repository.impl", - "dl.store.antivirus.impl", - "dl.store.impl", - "dockbar.add.portlets", + "control.panel.entry.class.default", "convert.processes", + "default.landing.page.path", "dl.file.entry.drafts.enabled", + "dl.file.entry.processors", "dl.repository.impl", + "dl.store.antivirus.impl", "dl.store.impl", "dockbar.add.portlets", "field.enable.com.liferay.portal.model.Contact.birthday", "field.enable.com.liferay.portal.model.Contact.male", "field.enable.com.liferay.portal.model.Organization.status", - "hot.deploy.listeners", - "javascript.fast.load", - "journal.article.form.add", - "journal.article.form.translate", - "journal.article.form.update", - "layout.form.add", - "layout.form.update", - "layout.set.form.update", - "layout.static.portlets.all", - "layout.template.cache.enabled", - "layout.types", + "hot.deploy.listeners", "javascript.fast.load", + "journal.article.form.add", "journal.article.form.translate", + "journal.article.form.update", "layout.form.add", "layout.form.update", + "layout.set.form.update", "layout.static.portlets.all", + "layout.template.cache.enabled", "layout.types", "layout.user.private.layouts.auto.create", "layout.user.private.layouts.enabled", "layout.user.private.layouts.power.user.required", "layout.user.public.layouts.auto.create", "layout.user.public.layouts.enabled", "layout.user.public.layouts.power.user.required", - "ldap.attrs.transformer.impl", - "locales.beta", - "login.create.account.allow.custom.password", - "login.events.post", - "login.events.pre", - "logout.events.post", - "logout.events.pre", - "mail.hook.impl", - "my.sites.show.private.sites.with.no.layouts", + "ldap.attrs.transformer.impl", "locales.beta", + "login.create.account.allow.custom.password", "login.events.post", + "login.events.pre", "logout.events.post", "logout.events.pre", + "mail.hook.impl", "my.sites.show.private.sites.with.no.layouts", "my.sites.show.public.sites.with.no.layouts", "my.sites.show.user.private.sites.with.no.layouts", "my.sites.show.user.public.sites.with.no.layouts", - "organizations.form.add.identification", - "organizations.form.add.main", + "organizations.form.add.identification", "organizations.form.add.main", "organizations.form.add.miscellaneous", "passwords.passwordpolicytoolkit.generator", - "passwords.passwordpolicytoolkit.static", - "phone.number.format.impl", + "passwords.passwordpolicytoolkit.static", "phone.number.format.impl", "phone.number.format.international.regexp", "phone.number.format.usa.regexp", "portlet.add.default.resource.check.enabled", "portlet.add.default.resource.check.whitelist", "portlet.add.default.resource.check.whitelist.actions", - "sanitizer.impl", - "servlet.session.create.events", - "servlet.session.destroy.events", - "servlet.service.events.post", - "servlet.service.events.pre", - "session.max.allowed", - "session.phishing.protected.attributes", - "session.store.password", - "sites.form.add.advanced", - "sites.form.add.main", - "sites.form.add.seo", - "sites.form.update.advanced", - "sites.form.update.main", - "sites.form.update.seo", - "social.bookmark.*", - "terms.of.use.required", - "theme.css.fast.load", - "theme.images.fast.load", - "theme.jsp.override.enabled", - "theme.loader.new.theme.id.on.import", - "theme.portlet.decorate.default", - "theme.portlet.sharing.default", - "theme.shortcut.icon", - "upgrade.processes", + "sanitizer.impl", "servlet.session.create.events", + "servlet.session.destroy.events", "servlet.service.events.post", + "servlet.service.events.pre", "session.max.allowed", + "session.phishing.protected.attributes", "session.store.password", + "sites.form.add.advanced", "sites.form.add.main", "sites.form.add.seo", + "sites.form.update.advanced", "sites.form.update.main", + "sites.form.update.seo", "social.bookmark.*", "terms.of.use.required", + "theme.css.fast.load", "theme.images.fast.load", + "theme.jsp.override.enabled", "theme.loader.new.theme.id.on.import", + "theme.portlet.decorate.default", "theme.portlet.sharing.default", + "theme.shortcut.icon", "upgrade.processes", "user.notification.event.confirmation.enabled", - "users.email.address.generator", - "users.email.address.required", - "users.form.add.identification", - "users.form.add.main", - "users.form.add.miscellaneous", - "users.form.my.account.identification", - "users.form.my.account.main", - "users.form.my.account.miscellaneous", - "users.form.update.identification", - "users.form.update.main", - "users.form.update.miscellaneous", - "users.full.name.generator", - "users.full.name.validator", - "users.image.max.height", - "users.image.max.width", - "users.screen.name.always.autogenerate", - "users.screen.name.generator", - "users.screen.name.validator", + "users.email.address.generator", "users.email.address.required", + "users.form.add.identification", "users.form.add.main", + "users.form.add.miscellaneous", "users.form.my.account.identification", + "users.form.my.account.main", "users.form.my.account.miscellaneous", + "users.form.update.identification", "users.form.update.main", + "users.form.update.miscellaneous", "users.full.name.generator", + "users.full.name.validator", "users.image.max.height", + "users.image.max.width", "users.screen.name.always.autogenerate", + "users.screen.name.generator", "users.screen.name.validator", "value.object.listener.*" }; @@ -2195,28 +2146,22 @@ else if (buildNumber < release.getBuildNumber()) { } private static final String[] _PROPS_KEYS_EVENTS = { - LOGIN_EVENTS_POST, - LOGIN_EVENTS_PRE, - LOGOUT_EVENTS_POST, - LOGOUT_EVENTS_PRE, - SERVLET_SERVICE_EVENTS_POST, + LOGIN_EVENTS_POST, LOGIN_EVENTS_PRE, LOGOUT_EVENTS_POST, + LOGOUT_EVENTS_PRE, SERVLET_SERVICE_EVENTS_POST, SERVLET_SERVICE_EVENTS_PRE }; private static final String[] _PROPS_KEYS_SESSION_EVENTS = { - SERVLET_SESSION_CREATE_EVENTS, - SERVLET_SESSION_DESTROY_EVENTS + SERVLET_SESSION_CREATE_EVENTS, SERVLET_SESSION_DESTROY_EVENTS }; private static final String[] _PROPS_VALUES_BOOLEAN = { - "auth.forward.by.last.path", - "captcha.check.portal.create_account", + "auth.forward.by.last.path", "captcha.check.portal.create_account", "dl.file.entry.drafts.enabled", "field.enable.com.liferay.portal.model.Contact.birthday", "field.enable.com.liferay.portal.model.Contact.male", "field.enable.com.liferay.portal.model.Organization.status", - "javascript.fast.load", - "layout.template.cache.enabled", + "javascript.fast.load", "layout.template.cache.enabled", "layout.user.private.layouts.auto.create", "layout.user.private.layouts.enabled", "layout.user.private.layouts.power.user.required", @@ -2228,23 +2173,17 @@ else if (buildNumber < release.getBuildNumber()) { "my.sites.show.public.sites.with.no.layouts", "my.sites.show.user.private.sites.with.no.layouts", "my.sites.show.user.public.sites.with.no.layouts", - "portlet.add.default.resource.check.enabled", - "session.store.password", - "terms.of.use.required", - "theme.css.fast.load", - "theme.images.fast.load", - "theme.jsp.override.enabled", - "theme.loader.new.theme.id.on.import", - "theme.portlet.decorate.default", + "portlet.add.default.resource.check.enabled", "session.store.password", + "terms.of.use.required", "theme.css.fast.load", + "theme.images.fast.load", "theme.jsp.override.enabled", + "theme.loader.new.theme.id.on.import", "theme.portlet.decorate.default", "theme.portlet.sharing.default", "user.notification.event.confirmation.enabled", - "users.email.address.required", - "users.screen.name.always.autogenerate" + "users.email.address.required", "users.screen.name.always.autogenerate" }; private static final String[] _PROPS_VALUES_INTEGER = { - "session.max.allowed", - "users.image.max.height", + "session.max.allowed", "users.image.max.height", "users.image.max.width", }; @@ -2252,43 +2191,27 @@ else if (buildNumber < release.getBuildNumber()) { }; private static final String[] _PROPS_VALUES_MERGE_STRING_ARRAY = { - "admin.default.group.names", - "admin.default.role.names", - "admin.default.user.group.names", - "asset.publisher.display.styles", + "admin.default.group.names", "admin.default.role.names", + "admin.default.user.group.names", "asset.publisher.display.styles", "company.settings.form.configuration", "company.settings.form.identification", - "company.settings.form.miscellaneous", - "convert.processes", - "dockbar.add.portlets", - "journal.article.form.add", - "journal.article.form.translate", - "journal.article.form.update", - "layout.form.add", - "layout.form.update", - "layout.set.form.update", - "layout.static.portlets.all", - "layout.types", - "organizations.form.add.identification", - "organizations.form.add.main", + "company.settings.form.miscellaneous", "convert.processes", + "dockbar.add.portlets", "journal.article.form.add", + "journal.article.form.translate", "journal.article.form.update", + "layout.form.add", "layout.form.update", "layout.set.form.update", + "layout.static.portlets.all", "layout.types", + "organizations.form.add.identification", "organizations.form.add.main", "organizations.form.add.miscellaneous", "portlet.add.default.resource.check.whitelist", "portlet.add.default.resource.check.whitelist.actions", - "session.phishing.protected.attributes", - "sites.form.add.advanced", - "sites.form.add.main", - "sites.form.add.seo", - "sites.form.update.advanced", - "sites.form.update.main", - "sites.form.update.seo", - "users.form.add.identification", - "users.form.add.main", - "users.form.add.miscellaneous", - "users.form.my.account.identification", - "users.form.my.account.main", + "session.phishing.protected.attributes", "sites.form.add.advanced", + "sites.form.add.main", "sites.form.add.seo", + "sites.form.update.advanced", "sites.form.update.main", + "sites.form.update.seo", "users.form.add.identification", + "users.form.add.main", "users.form.add.miscellaneous", + "users.form.my.account.identification", "users.form.my.account.main", "users.form.my.account.miscellaneous", - "users.form.update.identification", - "users.form.update.main", + "users.form.update.identification", "users.form.update.main", "users.form.update.miscellaneous" }; @@ -2306,8 +2229,7 @@ else if (buildNumber < release.getBuildNumber()) { "passwords.passwordpolicytoolkit.generator", "passwords.passwordpolicytoolkit.static", "phone.number.format.international.regexp", - "phone.number.format.usa.regexp", - "theme.shortcut.icon" + "phone.number.format.usa.regexp", "theme.shortcut.icon" }; private static Log _log = LogFactoryUtil.getLog( diff --git a/portal-impl/src/com/liferay/portal/deploy/hot/PluginPackageHotDeployListener.java b/portal-impl/src/com/liferay/portal/deploy/hot/PluginPackageHotDeployListener.java index aab9ebf8edfcaf..0c8c65433d9246 100644 --- a/portal-impl/src/com/liferay/portal/deploy/hot/PluginPackageHotDeployListener.java +++ b/portal-impl/src/com/liferay/portal/deploy/hot/PluginPackageHotDeployListener.java @@ -216,8 +216,8 @@ protected void initServiceComponent( } ServiceComponentLocalServiceUtil.initServiceComponent( - servletContext, classLoader, buildNamespace, buildNumber, - buildDate, buildAutoUpgrade); + servletContext, classLoader, buildNamespace, buildNumber, buildDate, + buildAutoUpgrade); } protected void reconfigureCaches(ClassLoader classLoader) throws Exception { diff --git a/portal-impl/src/com/liferay/portal/editor/fckeditor/receiver/impl/BaseCommandReceiver.java b/portal-impl/src/com/liferay/portal/editor/fckeditor/receiver/impl/BaseCommandReceiver.java index 4a2dea91673baa..79bc7122cc7ce5 100644 --- a/portal-impl/src/com/liferay/portal/editor/fckeditor/receiver/impl/BaseCommandReceiver.java +++ b/portal-impl/src/com/liferay/portal/editor/fckeditor/receiver/impl/BaseCommandReceiver.java @@ -397,8 +397,8 @@ private Document _createDocument() { } private Node _createRoot( - Document document, String command, String resourceType, - String path, String url) { + Document document, String command, String resourceType, String path, + String url) { Element rootElement = document.createElement("Connector"); diff --git a/portal-impl/src/com/liferay/portal/editor/fckeditor/receiver/impl/DocumentCommandReceiver.java b/portal-impl/src/com/liferay/portal/editor/fckeditor/receiver/impl/DocumentCommandReceiver.java index 95dd4ae4268d93..e62c144886fe2b 100644 --- a/portal-impl/src/com/liferay/portal/editor/fckeditor/receiver/impl/DocumentCommandReceiver.java +++ b/portal-impl/src/com/liferay/portal/editor/fckeditor/receiver/impl/DocumentCommandReceiver.java @@ -101,8 +101,8 @@ protected String fileUpload( serviceContext.setAddGuestPermissions(true); DLAppServiceUtil.addFileEntry( - repositoryId, folderId, title, contentType, title, - description, changeLog, inputStream, size, serviceContext); + repositoryId, folderId, title, contentType, title, description, + changeLog, inputStream, size, serviceContext); } catch (Exception e) { throw new FCKException(e); diff --git a/portal-impl/src/com/liferay/portal/events/AddDefaultDocumentLibraryStructuresAction.java b/portal-impl/src/com/liferay/portal/events/AddDefaultDocumentLibraryStructuresAction.java index 7823a6e529f3c8..76c8582cc2f697 100644 --- a/portal-impl/src/com/liferay/portal/events/AddDefaultDocumentLibraryStructuresAction.java +++ b/portal-impl/src/com/liferay/portal/events/AddDefaultDocumentLibraryStructuresAction.java @@ -189,9 +189,9 @@ protected void addDLRawMetadataStructures( DDMStructureLocalServiceUtil.addStructure( userId, groupId, - PortalUtil.getClassNameId(DLFileEntry.class), - name, nameMap, descriptionMap, structureElementRootXML, - "xml", DDMStructureConstants.TYPE_DEFAULT, serviceContext); + PortalUtil.getClassNameId(DLFileEntry.class), name, nameMap, + descriptionMap, structureElementRootXML, "xml", + DDMStructureConstants.TYPE_DEFAULT, serviceContext); } } } diff --git a/portal-impl/src/com/liferay/portal/events/AddDefaultLayoutPrototypesAction.java b/portal-impl/src/com/liferay/portal/events/AddDefaultLayoutPrototypesAction.java index fdaf66ac00674d..79e4b74f190707 100644 --- a/portal-impl/src/com/liferay/portal/events/AddDefaultLayoutPrototypesAction.java +++ b/portal-impl/src/com/liferay/portal/events/AddDefaultLayoutPrototypesAction.java @@ -194,8 +194,8 @@ protected void addWebContentPage( portletId); layout = LayoutLocalServiceUtil.updateLayout( - layout.getGroupId(), layout.isPrivateLayout(), - layout.getLayoutId(), layout.getTypeSettings()); + layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), + layout.getTypeSettings()); } protected void addWikiPage( diff --git a/portal-impl/src/com/liferay/portal/events/BaseDefaultDDMStructureAction.java b/portal-impl/src/com/liferay/portal/events/BaseDefaultDDMStructureAction.java index ffea10cb44876a..94a1cf3bb0957c 100644 --- a/portal-impl/src/com/liferay/portal/events/BaseDefaultDDMStructureAction.java +++ b/portal-impl/src/com/liferay/portal/events/BaseDefaultDDMStructureAction.java @@ -40,8 +40,8 @@ public abstract class BaseDefaultDDMStructureAction extends SimpleAction { protected void addDDMStructures( - long userId, long groupId, long classNameId, - String fileName, ServiceContext serviceContext) + long userId, long groupId, long classNameId, String fileName, + ServiceContext serviceContext) throws DocumentException, PortalException, SystemException { List structureElements = getDDMStructures(fileName); diff --git a/portal-impl/src/com/liferay/portal/events/ServicePreAction.java b/portal-impl/src/com/liferay/portal/events/ServicePreAction.java index aa6cdad50651e1..0faf08d9f2f5e8 100644 --- a/portal-impl/src/com/liferay/portal/events/ServicePreAction.java +++ b/portal-impl/src/com/liferay/portal/events/ServicePreAction.java @@ -1,2090 +1,2089 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portal.events; - -import com.liferay.portal.LayoutPermissionException; -import com.liferay.portal.NoSuchGroupException; -import com.liferay.portal.NoSuchLayoutException; -import com.liferay.portal.NoSuchUserException; -import com.liferay.portal.kernel.dao.orm.QueryUtil; -import com.liferay.portal.kernel.events.Action; -import com.liferay.portal.kernel.events.ActionException; -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.language.LanguageUtil; -import com.liferay.portal.kernel.lar.PortletDataHandlerKeys; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.portlet.LiferayPortletURL; -import com.liferay.portal.kernel.portlet.LiferayWindowState; -import com.liferay.portal.kernel.servlet.BrowserSnifferUtil; -import com.liferay.portal.kernel.servlet.HttpHeaders; -import com.liferay.portal.kernel.servlet.SessionErrors; -import com.liferay.portal.kernel.util.FriendlyURLNormalizerUtil; -import com.liferay.portal.kernel.util.GetterUtil; -import com.liferay.portal.kernel.util.HttpUtil; -import com.liferay.portal.kernel.util.LocaleUtil; -import com.liferay.portal.kernel.util.ParamUtil; -import com.liferay.portal.kernel.util.PropsKeys; -import com.liferay.portal.kernel.util.SessionParamUtil; -import com.liferay.portal.kernel.util.StringBundler; -import com.liferay.portal.kernel.util.StringPool; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.kernel.util.UnicodeProperties; -import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.model.ColorScheme; -import com.liferay.portal.model.Company; -import com.liferay.portal.model.Group; -import com.liferay.portal.model.GroupConstants; -import com.liferay.portal.model.Image; -import com.liferay.portal.model.Layout; -import com.liferay.portal.model.LayoutConstants; -import com.liferay.portal.model.LayoutSet; -import com.liferay.portal.model.LayoutTypePortlet; -import com.liferay.portal.model.LayoutTypePortletConstants; -import com.liferay.portal.model.Portlet; -import com.liferay.portal.model.RoleConstants; -import com.liferay.portal.model.Theme; -import com.liferay.portal.model.User; -import com.liferay.portal.model.impl.ColorSchemeImpl; -import com.liferay.portal.model.impl.VirtualLayout; -import com.liferay.portal.security.auth.PrincipalException; -import com.liferay.portal.security.permission.ActionKeys; -import com.liferay.portal.security.permission.PermissionChecker; -import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; -import com.liferay.portal.security.permission.PermissionThreadLocal; -import com.liferay.portal.service.GroupLocalServiceUtil; -import com.liferay.portal.service.ImageLocalServiceUtil; -import com.liferay.portal.service.LayoutLocalServiceUtil; -import com.liferay.portal.service.LayoutSetLocalServiceUtil; -import com.liferay.portal.service.PortletLocalServiceUtil; -import com.liferay.portal.service.RoleLocalServiceUtil; -import com.liferay.portal.service.ServiceContext; -import com.liferay.portal.service.ServiceContextFactory; -import com.liferay.portal.service.ServiceContextThreadLocal; -import com.liferay.portal.service.ThemeLocalServiceUtil; -import com.liferay.portal.service.UserLocalServiceUtil; -import com.liferay.portal.service.permission.GroupPermissionUtil; -import com.liferay.portal.service.permission.LayoutPermissionUtil; -import com.liferay.portal.service.permission.PortletPermissionUtil; -import com.liferay.portal.theme.ThemeDisplay; -import com.liferay.portal.theme.ThemeDisplayFactory; -import com.liferay.portal.util.CookieKeys; -import com.liferay.portal.util.LayoutClone; -import com.liferay.portal.util.LayoutCloneFactory; -import com.liferay.portal.util.PortalUtil; -import com.liferay.portal.util.PortletCategoryKeys; -import com.liferay.portal.util.PortletKeys; -import com.liferay.portal.util.PrefsPropsUtil; -import com.liferay.portal.util.PropsUtil; -import com.liferay.portal.util.PropsValues; -import com.liferay.portal.util.WebKeys; -import com.liferay.portal.webserver.WebServerServletTokenUtil; -import com.liferay.portlet.PortalPreferences; -import com.liferay.portlet.PortletPreferencesFactoryUtil; -import com.liferay.portlet.PortletURLImpl; -import com.liferay.portlet.asset.model.AssetEntry; -import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil; -import com.liferay.portlet.journal.NoSuchArticleException; -import com.liferay.portlet.journal.model.JournalArticle; -import com.liferay.portlet.journal.service.JournalArticleServiceUtil; -import com.liferay.portlet.sites.util.SitesUtil; - -import java.io.File; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.TimeZone; - -import javax.portlet.PortletMode; -import javax.portlet.PortletRequest; -import javax.portlet.PortletURL; -import javax.portlet.WindowState; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.commons.lang.time.StopWatch; -import org.apache.struts.Globals; - -/** - * @author Brian Wing Shun Chan - * @author Felix Ventero - * @author Jorge Ferrer - */ -public class ServicePreAction extends Action { - - public ServicePreAction() { - initImportLARFiles(); - } - - public ThemeDisplay initThemeDisplay( - HttpServletRequest request, HttpServletResponse response) - throws Exception { - - HttpSession session = request.getSession(); - - // Company - - Company company = PortalUtil.getCompany(request); - - long companyId = company.getCompanyId(); - - // CDN host - - String cdnHost = PortalUtil.getCDNHost(request); - - // Portal URL - - String portalURL = PortalUtil.getPortalURL(request); - - // Paths - - String contextPath = PortalUtil.getPathContext(); - String friendlyURLPrivateGroupPath = - PortalUtil.getPathFriendlyURLPrivateGroup(); - String friendlyURLPrivateUserPath = - PortalUtil.getPathFriendlyURLPrivateUser(); - String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic(); - String imagePath = cdnHost.concat(PortalUtil.getPathImage()); - String mainPath = PortalUtil.getPathMain(); - - String i18nPath = (String)request.getAttribute(WebKeys.I18N_PATH); - - if (Validator.isNotNull(i18nPath)) { - if (Validator.isNotNull(contextPath)) { - String i18nContextPath = contextPath.concat(i18nPath); - - friendlyURLPrivateGroupPath = StringUtil.replaceFirst( - friendlyURLPrivateGroupPath, contextPath, i18nContextPath); - friendlyURLPrivateUserPath = StringUtil.replaceFirst( - friendlyURLPrivateUserPath, contextPath, i18nContextPath); - friendlyURLPublicPath = StringUtil.replaceFirst( - friendlyURLPublicPath, contextPath, i18nContextPath); - mainPath = StringUtil.replaceFirst( - mainPath, contextPath, i18nContextPath); - } - else { - friendlyURLPrivateGroupPath = i18nPath.concat( - friendlyURLPrivateGroupPath); - friendlyURLPrivateUserPath = i18nPath.concat( - friendlyURLPrivateUserPath); - friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath); - mainPath = i18nPath.concat(mainPath); - } - } - - // Company logo - - StringBundler sb = new StringBundler(5); - - sb.append(imagePath); - sb.append("/company_logo?img_id="); - sb.append(company.getLogoId()); - sb.append("&t="); - sb.append(WebServerServletTokenUtil.getToken(company.getLogoId())); - - String companyLogo = sb.toString(); - - int companyLogoHeight = 0; - int companyLogoWidth = 0; - - Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo( - company.getLogoId()); - - if (companyLogoImage != null) { - companyLogoHeight = companyLogoImage.getHeight(); - companyLogoWidth = companyLogoImage.getWidth(); - } - - String realCompanyLogo = companyLogo; - int realCompanyLogoHeight = companyLogoHeight; - int realCompanyLogoWidth = companyLogoWidth; - - // User - - User user = null; - - try { - user = PortalUtil.getUser(request); - } - catch (NoSuchUserException nsue) { - if (_log.isWarnEnabled()) { - _log.warn(nsue.getMessage()); - } - - long userId = PortalUtil.getUserId(request); - - if (userId > 0) { - session.invalidate(); - } - - return null; - } - - boolean signedIn = false; - - if (user == null) { - user = company.getDefaultUser(); - } - else if (!user.isDefaultUser()) { - signedIn = true; - } - - if (PropsValues.BROWSER_CACHE_DISABLED || - (PropsValues.BROWSER_CACHE_SIGNED_IN_DISABLED && signedIn)) { - - response.setDateHeader(HttpHeaders.EXPIRES, 0); - response.setHeader( - HttpHeaders.CACHE_CONTROL, - HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE); - response.setHeader( - HttpHeaders.PRAGMA, HttpHeaders.PRAGMA_NO_CACHE_VALUE); - } - - User realUser = user; - - Long realUserId = (Long)session.getAttribute(WebKeys.USER_ID); - - if (realUserId != null) { - if (user.getUserId() != realUserId.longValue()) { - realUser = UserLocalServiceUtil.getUserById( - realUserId.longValue()); - } - } - - String doAsUserId = ParamUtil.getString(request, "doAsUserId"); - String doAsUserLanguageId = ParamUtil.getString( - request, "doAsUserLanguageId"); - long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId"); - - long refererPlid = ParamUtil.getLong(request, "refererPlid"); - - if (LayoutLocalServiceUtil.fetchLayout(refererPlid) == null) { - refererPlid = 0; - } - - String controlPanelCategory = ParamUtil.getString( - request, "controlPanelCategory"); - - // Permission checker - - PermissionChecker permissionChecker = - PermissionCheckerFactoryUtil.create(user, true); - - PermissionThreadLocal.setPermissionChecker(permissionChecker); - - // Locale - - Locale locale = (Locale)session.getAttribute(Globals.LOCALE_KEY); - - if (Validator.isNotNull(doAsUserLanguageId)) { - locale = LocaleUtil.fromLanguageId(doAsUserLanguageId); - } - - String i18nLanguageId = (String)request.getAttribute( - WebKeys.I18N_LANGUAGE_ID); - - if (Validator.isNotNull(i18nLanguageId)) { - locale = LocaleUtil.fromLanguageId(i18nLanguageId); - } - else if (locale == null) { - if (signedIn) { - locale = user.getLocale(); - } - else { - - // User previously set their preferred language - - String languageId = CookieKeys.getCookie( - request, CookieKeys.GUEST_LANGUAGE_ID, false); - - if (Validator.isNotNull(languageId)) { - locale = LocaleUtil.fromLanguageId(languageId); - } - - // Get locale from the request - - if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) { - locale = request.getLocale(); - } - - // Get locale from the default user - - if (locale == null) { - locale = user.getLocale(); - } - - if (Validator.isNull(locale.getCountry())) { - - // Locales must contain a country code - - locale = LanguageUtil.getLocale(locale.getLanguage()); - } - - if (!LanguageUtil.isAvailableLocale(locale)) { - locale = user.getLocale(); - } - } - - session.setAttribute(Globals.LOCALE_KEY, locale); - - LanguageUtil.updateCookie(request, response, locale); - } - - // Cookie support - - try { - - // LEP-4069 - - CookieKeys.validateSupportCookie(request); - } - catch (Exception e) { - CookieKeys.addSupportCookie(request, response); - } - - // Time zone - - TimeZone timeZone = user.getTimeZone(); - - if (timeZone == null) { - timeZone = company.getTimeZone(); - } - - // Layouts - - if (signedIn) { - updateUserLayouts(user); - } - - Layout layout = null; - List layouts = null; - - long plid = ParamUtil.getLong(request, "p_l_id"); - - if (plid > 0) { - layout = LayoutLocalServiceUtil.getLayout(plid); - - long sourceGroupId = ParamUtil.getLong(request, "p_v_l_s_g_id"); - - if ((sourceGroupId > 0) && (sourceGroupId != layout.getGroupId())) { - Group sourceGroup = GroupLocalServiceUtil.getGroup( - sourceGroupId); - - if (SitesUtil.isUserGroupLayoutSetViewable( - permissionChecker, layout.getGroup())) { - - layout = new VirtualLayout(layout, sourceGroup); - } - else { - layout = null; - } - } - } - else { - long groupId = ParamUtil.getLong(request, "groupId"); - boolean privateLayout = ParamUtil.getBoolean( - request, "privateLayout"); - long layoutId = ParamUtil.getLong(request, "layoutId"); - - if ((groupId > 0) && (layoutId > 0)) { - layout = LayoutLocalServiceUtil.getLayout( - groupId, privateLayout, layoutId); - } - } - - Boolean redirectToDefaultLayout = (Boolean)request.getAttribute( - WebKeys.REDIRECT_TO_DEFAULT_LAYOUT); - - if (redirectToDefaultLayout == null) { - redirectToDefaultLayout = Boolean.FALSE; - } - - if (layout != null) { - Group group = layout.getGroup(); - - if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) { - request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout); - } - - boolean isViewableGroup = LayoutPermissionUtil.contains( - permissionChecker, layout, controlPanelCategory, true, - ActionKeys.VIEW); - boolean isViewableStaging = GroupPermissionUtil.contains( - permissionChecker, group.getGroupId(), - ActionKeys.VIEW_STAGING); - - if (isViewableStaging) { - layouts = LayoutLocalServiceUtil.getLayouts( - layout.getGroupId(), layout.isPrivateLayout(), - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - } - else if (!isViewableGroup && group.isStagingGroup()) { - layout = null; - } - else if (!isLoginRequest(request) && - (!isViewableGroup || - (!redirectToDefaultLayout && - !LayoutPermissionUtil.contains( - permissionChecker, layout, false, - ActionKeys.VIEW)))) { - - if (user.isDefaultUser() && - PropsValues.AUTH_LOGIN_PROMPT_ENABLED) { - - throw new PrincipalException("User is not authenticated"); - } - - sb = new StringBundler(6); - - sb.append("User "); - sb.append(user.getUserId()); - sb.append(" is not allowed to access the "); - sb.append(layout.isPrivateLayout() ? "private": "public"); - sb.append(" pages of group "); - sb.append(layout.getGroupId()); - - if (_log.isWarnEnabled()) { - _log.warn(sb.toString()); - } - - throw new NoSuchLayoutException(sb.toString()); - } - else if (isLoginRequest(request) && !isViewableGroup) { - layout = null; - } - else if (group.isLayoutPrototype()) { - layouts = new ArrayList(); - } - else { - layouts = LayoutLocalServiceUtil.getLayouts( - layout.getGroupId(), layout.isPrivateLayout(), - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - - if (!group.isControlPanel()) { - doAsGroupId = 0; - } - } - } - - List unfilteredLayouts = layouts; - - if (layout == null) { - Object[] defaultLayout = getDefaultLayout(request, user, signedIn); - - layout = (Layout)defaultLayout[0]; - layouts = (List)defaultLayout[1]; - - request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE); - } - - Object[] viewableLayouts = getViewableLayouts( - request, user, permissionChecker, layout, layouts); - - String layoutSetLogo = null; - - layout = (Layout)viewableLayouts[0]; - layouts = (List)viewableLayouts[1]; - - Group group = null; - - if (layout != null) { - group = layout.getGroup(); - - if (!group.isControlPanel()) { - rememberVisitedGroupIds(request, group.getGroupId()); - } - } - - LayoutTypePortlet layoutTypePortlet = null; - - layouts = mergeAdditionalLayouts( - request, user, permissionChecker, layout, layouts); - - LayoutSet layoutSet = null; - - boolean hasCustomizeLayoutPermission = false; - boolean hasUpdateLayoutPermission = false; - - boolean customizedView = SessionParamUtil.getBoolean( - request, "customized_view", true); - - if (layout != null) { - hasCustomizeLayoutPermission = LayoutPermissionUtil.contains( - permissionChecker, layout, ActionKeys.CUSTOMIZE); - hasUpdateLayoutPermission = LayoutPermissionUtil.contains( - permissionChecker, layout, ActionKeys.UPDATE); - - layoutSet = layout.getLayoutSet(); - - if (company.isSiteLogo()) { - long logoId = 0; - - if (layoutSet.isLogo()) { - logoId = layoutSet.getLogoId(); - - if (logoId == 0) { - logoId = layoutSet.getLiveLogoId(); - } - } - else { - LayoutSet siblingLayoutSet = - LayoutSetLocalServiceUtil.getLayoutSet( - layout.getGroupId(), !layout.isPrivateLayout()); - - if (siblingLayoutSet.isLogo()) { - logoId = siblingLayoutSet.getLogoId(); - } - } - - if (logoId > 0) { - sb = new StringBundler(5); - - sb.append(imagePath); - sb.append("/layout_set_logo?img_id="); - sb.append(logoId); - sb.append("&t="); - sb.append(WebServerServletTokenUtil.getToken(logoId)); - - layoutSetLogo = sb.toString(); - - Image layoutSetLogoImage = - ImageLocalServiceUtil.getCompanyLogo(logoId); - - companyLogo = layoutSetLogo; - companyLogoHeight = layoutSetLogoImage.getHeight(); - companyLogoWidth = layoutSetLogoImage.getWidth(); - } - } - - plid = layout.getPlid(); - - // Updates to shared layouts are not reflected until the next time - // the user logs in because group layouts are cached in the session - - layout = (Layout)layout.clone(); - - layoutTypePortlet = (LayoutTypePortlet)layout.getLayoutType(); - - boolean customizable = layoutTypePortlet.isCustomizable(); - - if (!customizable || - (group.isLayoutPrototype() || group.isLayoutSetPrototype())) { - - customizedView = false; - } - - layoutTypePortlet.setCustomizedView(customizedView); - layoutTypePortlet.setUpdatePermission(hasUpdateLayoutPermission); - - if (signedIn && customizable && customizedView && - hasCustomizeLayoutPermission) { - - PortalPreferences portalPreferences = - PortletPreferencesFactoryUtil.getPortalPreferences( - companyId, user.getUserId(), true); - - layoutTypePortlet.setPortalPreferences(portalPreferences); - } - - LayoutClone layoutClone = LayoutCloneFactory.getInstance(); - - if (layoutClone != null) { - String typeSettings = layoutClone.get(request, plid); - - if (typeSettings != null) { - UnicodeProperties typeSettingsProperties = - new UnicodeProperties(true); - - typeSettingsProperties.load(typeSettings); - - String stateMax = typeSettingsProperties.getProperty( - LayoutTypePortletConstants.STATE_MAX); - String stateMin = typeSettingsProperties.getProperty( - LayoutTypePortletConstants.STATE_MIN); - String modeAbout = typeSettingsProperties.getProperty( - LayoutTypePortletConstants.MODE_ABOUT); - String modeConfig = typeSettingsProperties.getProperty( - LayoutTypePortletConstants.MODE_CONFIG); - String modeEdit = typeSettingsProperties.getProperty( - LayoutTypePortletConstants.MODE_EDIT); - String modeEditDefaults = - typeSettingsProperties.getProperty( - LayoutTypePortletConstants.MODE_EDIT_DEFAULTS); - String modeEditGuest = typeSettingsProperties.getProperty( - LayoutTypePortletConstants.MODE_EDIT_GUEST); - String modeHelp = typeSettingsProperties.getProperty( - LayoutTypePortletConstants.MODE_HELP); - String modePreview = typeSettingsProperties.getProperty( - LayoutTypePortletConstants.MODE_PREVIEW); - String modePrint = typeSettingsProperties.getProperty( - LayoutTypePortletConstants.MODE_PRINT); - - layoutTypePortlet.setStateMax(stateMax); - layoutTypePortlet.setStateMin(stateMin); - layoutTypePortlet.setModeAbout(modeAbout); - layoutTypePortlet.setModeConfig(modeConfig); - layoutTypePortlet.setModeEdit(modeEdit); - layoutTypePortlet.setModeEditDefaults(modeEditDefaults); - layoutTypePortlet.setModeEditGuest(modeEditGuest); - layoutTypePortlet.setModeHelp(modeHelp); - layoutTypePortlet.setModePreview(modePreview); - layoutTypePortlet.setModePrint(modePrint); - } - } - - request.setAttribute(WebKeys.LAYOUT, layout); - request.setAttribute(WebKeys.LAYOUTS, layouts); - - if (layout.isPrivateLayout() || - !PropsValues.PERMISSIONS_LAYOUT_PUBLIC_CHECK_GUEST_ENABLED) { - - permissionChecker.setCheckGuest(false); - } - } - - // Scope - - long scopeGroupId = PortalUtil.getScopeGroupId(request); - long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId); - - // Theme and color scheme - - Theme theme = null; - ColorScheme colorScheme = null; - - boolean wapTheme = BrowserSnifferUtil.isWap(request); - - if ((layout != null) && group.isControlPanel()) { - String themeId = PrefsPropsUtil.getString( - companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID); - String colorSchemeId = - ColorSchemeImpl.getDefaultRegularColorSchemeId(); - - theme = ThemeLocalServiceUtil.getTheme( - companyId, themeId, wapTheme); - colorScheme = ThemeLocalServiceUtil.getColorScheme( - companyId, theme.getThemeId(), colorSchemeId, wapTheme); - - if (!wapTheme && theme.isWapTheme()) { - theme = ThemeLocalServiceUtil.getTheme( - companyId, - PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID, false); - colorScheme = ThemeLocalServiceUtil.getColorScheme( - companyId, theme.getThemeId(), colorSchemeId, false); - } - - request.setAttribute(WebKeys.THEME, theme); - request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme); - } - - boolean themeCssFastLoad = SessionParamUtil.getBoolean( - request, "css_fast_load", PropsValues.THEME_CSS_FAST_LOAD); - boolean themeImagesFastLoad = SessionParamUtil.getBoolean( - request, "images_fast_load", PropsValues.THEME_IMAGES_FAST_LOAD); - - boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED; - - if (themeJsBarebone) { - if (signedIn) { - themeJsBarebone = false; - } - } - - boolean themeJsFastLoad = SessionParamUtil.getBoolean( - request, "js_fast_load", PropsValues.JAVASCRIPT_FAST_LOAD); - - String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0"); - - lifecycle = ParamUtil.getString(request, "p_t_lifecycle", lifecycle); - - boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated"); - - String facebookCanvasPageURL = (String)request.getAttribute( - WebKeys.FACEBOOK_CANVAS_PAGE_URL); - - boolean widget = false; - - Boolean widgetObj = (Boolean)request.getAttribute(WebKeys.WIDGET); - - if (widgetObj != null) { - widget = widgetObj.booleanValue(); - } - - // Theme display - - ThemeDisplay themeDisplay = ThemeDisplayFactory.create(); - - // Set the CDN host, portal URL, and Facebook application ID first - // because other methods (setLookAndFeel) depend on them being set - - themeDisplay.setCDNHost(cdnHost); - themeDisplay.setPortalURL(portalURL); - themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL); - themeDisplay.setWidget(widget); - - themeDisplay.setCompany(company); - themeDisplay.setCompanyLogo(companyLogo); - themeDisplay.setCompanyLogoHeight(companyLogoHeight); - themeDisplay.setCompanyLogoWidth(companyLogoWidth); - themeDisplay.setRealCompanyLogo(realCompanyLogo); - themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight); - themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth); - themeDisplay.setUser(user); - themeDisplay.setRealUser(realUser); - themeDisplay.setDoAsUserId(doAsUserId); - themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId); - themeDisplay.setDoAsGroupId(doAsGroupId); - themeDisplay.setRefererPlid(refererPlid); - themeDisplay.setControlPanelCategory(controlPanelCategory); - themeDisplay.setLayoutSet(layoutSet); - themeDisplay.setLayoutSetLogo(layoutSetLogo); - themeDisplay.setLayout(layout); - themeDisplay.setLayouts(layouts); - themeDisplay.setUnfilteredLayouts(unfilteredLayouts); - themeDisplay.setPlid(plid); - themeDisplay.setLayoutTypePortlet(layoutTypePortlet); - themeDisplay.setScopeGroupId(scopeGroupId); - themeDisplay.setParentGroupId(parentGroupId); - themeDisplay.setSignedIn(signedIn); - themeDisplay.setPermissionChecker(permissionChecker); - themeDisplay.setLocale(locale); - themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale)); - themeDisplay.setI18nLanguageId(i18nLanguageId); - themeDisplay.setI18nPath(i18nPath); - themeDisplay.setTimeZone(timeZone); - themeDisplay.setLookAndFeel(theme, colorScheme); - themeDisplay.setThemeCssFastLoad(themeCssFastLoad); - themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad); - themeDisplay.setThemeJsBarebone(themeJsBarebone); - themeDisplay.setThemeJsFastLoad(themeJsFastLoad); - themeDisplay.setServerName(request.getServerName()); - themeDisplay.setServerPort(request.getServerPort()); - themeDisplay.setSecure(PortalUtil.isSecure(request)); - themeDisplay.setLifecycle(lifecycle); - themeDisplay.setLifecycleAction(lifecycle.equals("1")); - themeDisplay.setLifecycleRender(lifecycle.equals("0")); - themeDisplay.setLifecycleResource(lifecycle.equals("2")); - themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request)); - themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request)); - themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request)); - themeDisplay.setIsolated(isolated); - themeDisplay.setPathApplet(contextPath.concat("/applets")); - themeDisplay.setPathCms(contextPath.concat("/cms")); - themeDisplay.setPathContext(contextPath); - themeDisplay.setPathFlash(contextPath.concat("/flash")); - themeDisplay.setPathFriendlyURLPrivateGroup( - friendlyURLPrivateGroupPath); - themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath); - themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath); - themeDisplay.setPathImage(imagePath); - themeDisplay.setPathJavaScript( - cdnHost.concat(contextPath).concat("/html/js")); - themeDisplay.setPathMain(mainPath); - themeDisplay.setPathSound(contextPath.concat("/html/sound")); - - // Icons - - themeDisplay.setShowAddContentIcon(false); - themeDisplay.setShowControlPanelIcon(signedIn); - themeDisplay.setShowHomeIcon(true); - themeDisplay.setShowMyAccountIcon(signedIn); - themeDisplay.setShowPageSettingsIcon(false); - themeDisplay.setShowPortalIcon(true); - themeDisplay.setShowSignInIcon(!signedIn); - themeDisplay.setShowSignOutIcon(signedIn); - - boolean showSiteContentIcon = false; - - long controlPanelPlid = 0; - - if (signedIn) { - Group controlPanelGroup = GroupLocalServiceUtil.getGroup( - companyId, GroupConstants.CONTROL_PANEL); - - controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid( - controlPanelGroup.getGroupId(), true); - - List siteContentPortlets = - PortalUtil.getControlPanelPortlets( - PortletCategoryKeys.CONTENT, themeDisplay); - - Portlet groupPagesPortlet = PortletLocalServiceUtil.getPortletById( - PortletKeys.GROUP_PAGES); - - siteContentPortlets.remove(groupPagesPortlet); - - Portlet siteMembershipsAdminPortlet = - PortletLocalServiceUtil.getPortletById( - PortletKeys.SITE_MEMBERSHIPS_ADMIN); - - siteContentPortlets.remove(siteMembershipsAdminPortlet); - - Portlet siteSettingsPortlet = - PortletLocalServiceUtil.getPortletById( - PortletKeys.SITE_SETTINGS); - - siteContentPortlets.remove(siteSettingsPortlet); - - showSiteContentIcon = PortletPermissionUtil.contains( - permissionChecker, scopeGroupId, controlPanelPlid, - siteContentPortlets, ActionKeys.VIEW); - } - - themeDisplay.setShowSiteContentIcon(showSiteContentIcon); - - themeDisplay.setShowStagingIcon(false); - - // Session - - if (PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID && - !CookieKeys.hasSessionId(request)) { - - themeDisplay.setAddSessionIdToURL(true); - themeDisplay.setSessionId(session.getId()); - } - - // URLs - - String urlControlPanel = friendlyURLPrivateGroupPath.concat( - GroupConstants.CONTROL_PANEL_FRIENDLY_URL); - - if (Validator.isNotNull(doAsUserId)) { - urlControlPanel = HttpUtil.addParameter( - urlControlPanel, "doAsUserId", doAsUserId); - } - - if (scopeGroupId > 0) { - urlControlPanel = HttpUtil.addParameter( - urlControlPanel, "doAsGroupId", scopeGroupId); - } - - if (refererPlid > 0) { - urlControlPanel = HttpUtil.addParameter( - urlControlPanel, "refererPlid", refererPlid); - } - else if (plid > 0) { - urlControlPanel = HttpUtil.addParameter( - urlControlPanel, "refererPlid", plid); - } - - if (themeDisplay.isAddSessionIdToURL()) { - urlControlPanel = PortalUtil.getURLWithSessionId( - urlControlPanel, session.getId()); - } - - themeDisplay.setURLControlPanel(urlControlPanel); - - String siteContentURL = urlControlPanel; - - siteContentURL = HttpUtil.addParameter( - siteContentURL, "controlPanelCategory", - PortletCategoryKeys.CONTENT); - - themeDisplay.setURLSiteContent(siteContentURL); - - String currentURL = PortalUtil.getCurrentURL(request); - - themeDisplay.setURLCurrent(currentURL); - - String urlHome = PortalUtil.getHomeURL(request); - - themeDisplay.setURLHome(urlHome); - - if (layout != null) { - if (layout.isTypePortlet()) { - boolean freeformLayout = - layoutTypePortlet.getLayoutTemplateId().equals("freeform"); - - themeDisplay.setFreeformLayout(freeformLayout); - - if (hasUpdateLayoutPermission) { - themeDisplay.setShowAddContentIconPermission(true); - - if (!LiferayWindowState.isMaximized(request)) { - themeDisplay.setShowAddContentIcon(true); - } - - themeDisplay.setShowLayoutTemplatesIcon(true); - - if (!group.isUser()) { - themeDisplay.setShowPageCustomizationIcon(true); - } - - themeDisplay.setURLAddContent( - "Liferay.LayoutConfiguration.toggle('".concat( - PortletKeys.LAYOUT_CONFIGURATION).concat("');")); - - themeDisplay.setURLLayoutTemplates( - "Liferay.LayoutConfiguration.showTemplates();"); - } - - if (hasCustomizeLayoutPermission && customizedView) { - themeDisplay.setShowAddContentIconPermission(true); - - if (!LiferayWindowState.isMaximized(request)) { - themeDisplay.setShowAddContentIcon(true); - } - - themeDisplay.setURLAddContent( - "Liferay.LayoutConfiguration.toggle('".concat( - PortletKeys.LAYOUT_CONFIGURATION).concat("');")); - } - } - - if (hasUpdateLayoutPermission) { - themeDisplay.setShowPageSettingsIcon(true); - - LiferayPortletURL pageSettingsURL = new PortletURLImpl( - request, PortletKeys.LAYOUTS_ADMIN, controlPanelPlid, - PortletRequest.RENDER_PHASE); - - pageSettingsURL.setControlPanelCategory( - _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + - PortletKeys.LAYOUTS_ADMIN); - pageSettingsURL.setParameter( - "struts_action", "/layouts_admin/edit_layouts"); - - if (layout.isPrivateLayout()) { - pageSettingsURL.setParameter("tabs1", "private-pages"); - } - else { - pageSettingsURL.setParameter("tabs1", "public-pages"); - } - - pageSettingsURL.setParameter("closeRedirect", currentURL); - pageSettingsURL.setParameter( - "groupId", String.valueOf(scopeGroupId)); - pageSettingsURL.setParameter("selPlid", String.valueOf(plid)); - pageSettingsURL.setPortletMode(PortletMode.VIEW); - pageSettingsURL.setWindowState(LiferayWindowState.POP_UP); - - themeDisplay.setURLPageSettings(pageSettingsURL); - - boolean site = group.isSite(); - - if (!site && group.isStagingGroup()) { - Group liveGroup = group.getLiveGroup(); - - site = liveGroup.isSite(); - } - - if (site && - GroupPermissionUtil.contains( - permissionChecker, scopeGroupId, - ActionKeys.ASSIGN_MEMBERS)) { - - themeDisplay.setShowManageSiteMembershipsIcon(true); - - LiferayPortletURL manageSiteMembershipsURL = - new PortletURLImpl( - request, PortletKeys.SITE_MEMBERSHIPS_ADMIN, - controlPanelPlid, PortletRequest.RENDER_PHASE); - - manageSiteMembershipsURL.setControlPanelCategory( - _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + - PortletKeys.SITE_MEMBERSHIPS_ADMIN); - manageSiteMembershipsURL.setParameter( - "struts_action", "/sites_admin/edit_site_assignments"); - manageSiteMembershipsURL.setParameter( - "groupId", String.valueOf(scopeGroupId)); - manageSiteMembershipsURL.setParameter( - "selPlid", String.valueOf(plid)); - manageSiteMembershipsURL.setPortletMode(PortletMode.VIEW); - manageSiteMembershipsURL.setWindowState( - LiferayWindowState.POP_UP); - - themeDisplay.setURLManageSiteMemberships( - manageSiteMembershipsURL); - } - else { - themeDisplay.setShowManageSiteMembershipsIcon(false); - } - } - - boolean hasAddLayoutGroupPermission = GroupPermissionUtil.contains( - permissionChecker, scopeGroupId, ActionKeys.ADD_LAYOUT); - boolean hasAddLayoutLayoutPermission = - LayoutPermissionUtil.contains( - permissionChecker, layout, ActionKeys.ADD_LAYOUT); - boolean hasManageLayoutsGroupPermission = - GroupPermissionUtil.contains( - permissionChecker, scopeGroupId, ActionKeys.MANAGE_LAYOUTS); - boolean hasManageStagingPermission = GroupPermissionUtil.contains( - permissionChecker, scopeGroupId, ActionKeys.MANAGE_STAGING); - boolean hasPublishStagingPermission = GroupPermissionUtil.contains( - permissionChecker, scopeGroupId, ActionKeys.PUBLISH_STAGING); - boolean hasUpdateGroupPermission = GroupPermissionUtil.contains( - permissionChecker, scopeGroupId, ActionKeys.UPDATE); - boolean hasViewStagingPermission = GroupPermissionUtil.contains( - permissionChecker, scopeGroupId, ActionKeys.VIEW_STAGING); - - if (!group.isControlPanel() && !group.isUser() && - !group.isUserGroup() && hasUpdateGroupPermission) { - - themeDisplay.setShowSiteSettingsIcon(true); - - LiferayPortletURL siteSettingsURL = new PortletURLImpl( - request, PortletKeys.SITE_SETTINGS, controlPanelPlid, - PortletRequest.RENDER_PHASE); - - siteSettingsURL.setControlPanelCategory( - _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + - PortletKeys.SITE_SETTINGS); - siteSettingsURL.setParameter( - "struts_action", "/sites_admin/edit_site"); - siteSettingsURL.setParameter("closeRedirect", currentURL); - siteSettingsURL.setParameter( - "groupId", String.valueOf(scopeGroupId)); - siteSettingsURL.setPortletMode(PortletMode.VIEW); - siteSettingsURL.setWindowState(LiferayWindowState.POP_UP); - - themeDisplay.setURLSiteSettings(siteSettingsURL); - } - - if (!group.isLayoutPrototype() && - (hasAddLayoutGroupPermission || hasAddLayoutLayoutPermission || - hasManageLayoutsGroupPermission || hasUpdateGroupPermission)) { - - themeDisplay.setShowSiteMapSettingsIcon(true); - - LiferayPortletURL siteMapSettingsURL = new PortletURLImpl( - request, PortletKeys.LAYOUTS_ADMIN, controlPanelPlid, - PortletRequest.RENDER_PHASE); - - siteMapSettingsURL.setControlPanelCategory( - _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + - PortletKeys.LAYOUTS_ADMIN); - siteMapSettingsURL.setParameter( - "struts_action", "/layouts_admin/edit_layouts"); - - if (layout.isPrivateLayout()) { - siteMapSettingsURL.setParameter("tabs1", "private-pages"); - } - else { - siteMapSettingsURL.setParameter("tabs1", "public-pages"); - } - - siteMapSettingsURL.setParameter("closeRedirect", currentURL); - siteMapSettingsURL.setParameter( - "groupId", String.valueOf(scopeGroupId)); - siteMapSettingsURL.setParameter( - "selPlid", String.valueOf(plid)); - siteMapSettingsURL.setPortletMode(PortletMode.VIEW); - siteMapSettingsURL.setWindowState(LiferayWindowState.POP_UP); - - themeDisplay.setURLSiteMapSettings(siteMapSettingsURL); - } - - if (group.hasStagingGroup() && !group.isStagingGroup()) { - themeDisplay.setShowAddContentIcon(false); - themeDisplay.setShowLayoutTemplatesIcon(false); - themeDisplay.setShowPageSettingsIcon(false); - themeDisplay.setURLPublishToLive(null); - } - - if (group.isControlPanel()) { - themeDisplay.setShowPageSettingsIcon(false); - themeDisplay.setURLPublishToLive(null); - } - - // LEP-4987 - - if (group.isStaged() || group.isStagingGroup()) { - if (hasManageStagingPermission || hasPublishStagingPermission || - hasUpdateLayoutPermission || hasViewStagingPermission) { - - themeDisplay.setShowStagingIcon(true); - } - - if (hasPublishStagingPermission) { - PortletURL publishToLiveURL = new PortletURLImpl( - request, PortletKeys.LAYOUTS_ADMIN, plid, - PortletRequest.RENDER_PHASE); - - publishToLiveURL.setParameter( - "struts_action", "/layouts_admin/publish_layouts"); - - if (layout.isPrivateLayout()) { - publishToLiveURL.setParameter("tabs1", "private-pages"); - } - else { - publishToLiveURL.setParameter("tabs1", "public-pages"); - } - - publishToLiveURL.setParameter("pagesRedirect", currentURL); - publishToLiveURL.setParameter( - "groupId", String.valueOf(scopeGroupId)); - publishToLiveURL.setParameter( - "selPlid", String.valueOf(plid)); - publishToLiveURL.setPortletMode(PortletMode.VIEW); - publishToLiveURL.setWindowState( - LiferayWindowState.EXCLUSIVE); - - themeDisplay.setURLPublishToLive(publishToLiveURL); - } - } - - PortletURLImpl myAccountURL = new PortletURLImpl( - request, PortletKeys.MY_ACCOUNT, controlPanelPlid, - PortletRequest.RENDER_PHASE); - - if (scopeGroupId > 0) { - myAccountURL.setDoAsGroupId(scopeGroupId); - } - - myAccountURL.setParameter("struts_action", "/my_account/edit_user"); - myAccountURL.setPortletMode(PortletMode.VIEW); - - if (refererPlid > 0) { - myAccountURL.setRefererPlid(refererPlid); - } - else { - myAccountURL.setRefererPlid(plid); - } - - myAccountURL.setWindowState(WindowState.MAXIMIZED); - - themeDisplay.setURLMyAccount(myAccountURL); - } - - if ((!user.isActive()) || - (PrefsPropsUtil.getBoolean( - companyId, PropsKeys.TERMS_OF_USE_REQUIRED) && - !user.isAgreedToTermsOfUse())) { - - themeDisplay.setShowAddContentIcon(false); - themeDisplay.setShowMyAccountIcon(false); - themeDisplay.setShowPageSettingsIcon(false); - } - - if (group.isLayoutPrototype()) { - themeDisplay.setShowControlPanelIcon(false); - themeDisplay.setShowHomeIcon(false); - themeDisplay.setShowManageSiteMembershipsIcon(false); - themeDisplay.setShowMyAccountIcon(false); - themeDisplay.setShowPageCustomizationIcon(false); - themeDisplay.setShowPageSettingsIcon(true); - themeDisplay.setShowPortalIcon(false); - themeDisplay.setShowSignInIcon(false); - themeDisplay.setShowSignOutIcon(false); - themeDisplay.setShowSiteContentIcon(false); - themeDisplay.setShowSiteSettingsIcon(false); - themeDisplay.setShowStagingIcon(false); - } - - if (group.isLayoutSetPrototype()) { - themeDisplay.setShowPageCustomizationIcon(false); - themeDisplay.setShowSiteSettingsIcon(false); - } - - if (group.hasStagingGroup() && !group.isStagingGroup()) { - themeDisplay.setShowLayoutTemplatesIcon(false); - themeDisplay.setShowPageCustomizationIcon(false); - themeDisplay.setShowPageSettingsIcon(false); - themeDisplay.setShowSiteContentIcon(false); - themeDisplay.setShowSiteMapSettingsIcon(false); - themeDisplay.setShowSiteSettingsIcon(false); - } - - themeDisplay.setURLPortal(portalURL.concat(contextPath)); - - String urlSignIn = mainPath.concat("/portal/login"); - - if (layout != null) { - urlSignIn = HttpUtil.addParameter( - urlSignIn, "p_l_id", layout.getPlid()); - } - - themeDisplay.setURLSignIn(urlSignIn); - - themeDisplay.setURLSignOut(mainPath.concat("/portal/logout")); - - PortletURL updateManagerURL = new PortletURLImpl( - request, PortletKeys.UPDATE_MANAGER, plid, - PortletRequest.RENDER_PHASE); - - updateManagerURL.setParameter("struts_action", "/update_manager/view"); - updateManagerURL.setPortletMode(PortletMode.VIEW); - updateManagerURL.setWindowState(WindowState.MAXIMIZED); - - themeDisplay.setURLUpdateManager(updateManagerURL); - - return themeDisplay; - } - - @Override - public void run(HttpServletRequest request, HttpServletResponse response) - throws ActionException { - - StopWatch stopWatch = null; - - if (_log.isDebugEnabled()) { - stopWatch = new StopWatch(); - - stopWatch.start(); - } - - try { - servicePre(request, response); - } - catch (Exception e) { - throw new ActionException(e); - } - - if (_log.isDebugEnabled()) { - _log.debug("Running takes " + stopWatch.getTime() + " ms"); - } - } - - protected void addDefaultLayoutsByLAR( - long userId, long groupId, boolean privateLayout, File larFile) - throws PortalException, SystemException { - - Map parameterMap = new HashMap(); - - parameterMap.put( - PortletDataHandlerKeys.PERMISSIONS, - new String[] {Boolean.TRUE.toString()}); - parameterMap.put( - PortletDataHandlerKeys.PORTLET_DATA, - new String[] {Boolean.TRUE.toString()}); - parameterMap.put( - PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT, - new String[] {Boolean.TRUE.toString()}); - parameterMap.put( - PortletDataHandlerKeys.PORTLET_SETUP, - new String[] {Boolean.TRUE.toString()}); - parameterMap.put( - PortletDataHandlerKeys.USER_PERMISSIONS, - new String[] {Boolean.FALSE.toString()}); - - LayoutLocalServiceUtil.importLayouts( - userId, groupId, privateLayout, parameterMap, larFile); - } - - protected void addDefaultUserPrivateLayoutByProperties( - long userId, long groupId) - throws PortalException, SystemException { - - String friendlyURL = getFriendlyURL( - PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_FRIENDLY_URL); - - ServiceContext serviceContext = new ServiceContext(); - - Layout layout = LayoutLocalServiceUtil.addLayout( - userId, groupId, true, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID, - PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_NAME, StringPool.BLANK, - StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL, - serviceContext); - - LayoutTypePortlet layoutTypePortlet = - (LayoutTypePortlet)layout.getLayoutType(); - - layoutTypePortlet.setLayoutTemplateId( - 0, PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_TEMPLATE_ID, false); - - for (int i = 0; i < 10; i++) { - String columnId = "column-" + i; - String portletIds = PropsUtil.get( - PropsKeys.DEFAULT_USER_PRIVATE_LAYOUT_COLUMN + i); - - String[] portletIdsArray = StringUtil.split(portletIds); - - layoutTypePortlet.addPortletIds( - 0, portletIdsArray, columnId, false); - } - - LayoutLocalServiceUtil.updateLayout( - layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), - layout.getTypeSettings()); - - boolean updateLayoutSet = false; - - LayoutSet layoutSet = layout.getLayoutSet(); - - if (Validator.isNotNull( - PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_THEME_ID)) { - - layoutSet.setThemeId( - PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_THEME_ID); - - updateLayoutSet = true; - } - - if (Validator.isNotNull( - PropsValues. - DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_COLOR_SCHEME_ID)) { - - layoutSet.setColorSchemeId( - PropsValues. - DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_COLOR_SCHEME_ID); - - updateLayoutSet = true; - } - - if (Validator.isNotNull( - PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_THEME_ID)) { - - layoutSet.setWapThemeId( - PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_THEME_ID); - - updateLayoutSet = true; - } - - if (Validator.isNotNull( - PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_COLOR_SCHEME_ID)) { - - layoutSet.setWapColorSchemeId( - PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_COLOR_SCHEME_ID); - - updateLayoutSet = true; - } - - if (updateLayoutSet) { - LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet); - } - } - - protected void addDefaultUserPrivateLayouts(User user) - throws PortalException, SystemException { - - Group userGroup = user.getGroup(); - - if (privateLARFile != null) { - addDefaultLayoutsByLAR( - user.getUserId(), userGroup.getGroupId(), true, privateLARFile); - } - else { - addDefaultUserPrivateLayoutByProperties( - user.getUserId(), userGroup.getGroupId()); - } - } - - protected void addDefaultUserPublicLayoutByProperties( - long userId, long groupId) - throws PortalException, SystemException { - - String friendlyURL = getFriendlyURL( - PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_FRIENDLY_URL); - - ServiceContext serviceContext = new ServiceContext(); - - Layout layout = LayoutLocalServiceUtil.addLayout( - userId, groupId, false, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID, - PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_NAME, StringPool.BLANK, - StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL, - serviceContext); - - LayoutTypePortlet layoutTypePortlet = - (LayoutTypePortlet)layout.getLayoutType(); - - layoutTypePortlet.setLayoutTemplateId( - 0, PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_TEMPLATE_ID, false); - - for (int i = 0; i < 10; i++) { - String columnId = "column-" + i; - String portletIds = PropsUtil.get( - PropsKeys.DEFAULT_USER_PUBLIC_LAYOUT_COLUMN + i); - - String[] portletIdsArray = StringUtil.split(portletIds); - - layoutTypePortlet.addPortletIds( - 0, portletIdsArray, columnId, false); - } - - LayoutLocalServiceUtil.updateLayout( - layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), - layout.getTypeSettings()); - - boolean updateLayoutSet = false; - - LayoutSet layoutSet = layout.getLayoutSet(); - - if (Validator.isNotNull( - PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID)) { - - layoutSet.setThemeId( - PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID); - - updateLayoutSet = true; - } - - if (Validator.isNotNull( - PropsValues. - DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID)) { - - layoutSet.setColorSchemeId( - PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID); - - updateLayoutSet = true; - } - - if (Validator.isNotNull( - PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID)) { - - layoutSet.setWapThemeId( - PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID); - - updateLayoutSet = true; - } - - if (Validator.isNotNull( - PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID)) { - - layoutSet.setWapColorSchemeId( - PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID); - - updateLayoutSet = true; - } - - if (updateLayoutSet) { - LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet); - } - } - - protected void addDefaultUserPublicLayouts(User user) - throws PortalException, SystemException { - - Group userGroup = user.getGroup(); - - if (publicLARFile != null) { - addDefaultLayoutsByLAR( - user.getUserId(), userGroup.getGroupId(), false, publicLARFile); - } - else { - addDefaultUserPublicLayoutByProperties( - user.getUserId(), userGroup.getGroupId()); - } - } - - protected void deleteDefaultUserPrivateLayouts(User user) - throws PortalException, SystemException { - - Group userGroup = user.getGroup(); - - ServiceContext serviceContext = new ServiceContext(); - - LayoutLocalServiceUtil.deleteLayouts( - userGroup.getGroupId(), true, serviceContext); - } - - protected void deleteDefaultUserPublicLayouts(User user) - throws PortalException, SystemException { - - Group userGroup = user.getGroup(); - - ServiceContext serviceContext = new ServiceContext(); - - LayoutLocalServiceUtil.deleteLayouts( - userGroup.getGroupId(), false, serviceContext); - } - - protected Object[] getDefaultLayout( - HttpServletRequest request, User user, boolean signedIn) - throws PortalException, SystemException { - - // Check the virtual host - - LayoutSet layoutSet = (LayoutSet)request.getAttribute( - WebKeys.VIRTUAL_HOST_LAYOUT_SET); - - if (layoutSet != null) { - List layouts = LayoutLocalServiceUtil.getLayouts( - layoutSet.getGroupId(), layoutSet.isPrivateLayout(), - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - - if (layouts.size() > 0) { - Layout layout = layouts.get(0); - - return new Object[] {layout, layouts}; - } - } - - Layout layout = null; - List layouts = null; - - if (signedIn) { - - // Check the user's personal layouts - - Group userGroup = user.getGroup(); - - layouts = LayoutLocalServiceUtil.getLayouts( - userGroup.getGroupId(), true, - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - - if (layouts.size() == 0) { - layouts = LayoutLocalServiceUtil.getLayouts( - userGroup.getGroupId(), false, - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - } - - if (layouts.size() > 0) { - layout = layouts.get(0); - } - - // Check the user's sites - - if (layout == null) { - LinkedHashMap groupParams = - new LinkedHashMap(); - - groupParams.put("usersGroups", new Long(user.getUserId())); - - List groups = GroupLocalServiceUtil.search( - user.getCompanyId(), null, null, groupParams, - QueryUtil.ALL_POS, QueryUtil.ALL_POS); - - for (Group group : groups) { - layouts = LayoutLocalServiceUtil.getLayouts( - group.getGroupId(), true, - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - - if (layouts.size() == 0) { - layouts = LayoutLocalServiceUtil.getLayouts( - group.getGroupId(), false, - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - } - - if (layouts.size() > 0) { - layout = layouts.get(0); - - break; - } - } - } - } - - if (layout == null) { - - // Check the Guest site - - Group guestGroup = GroupLocalServiceUtil.getGroup( - user.getCompanyId(), GroupConstants.GUEST); - - layouts = LayoutLocalServiceUtil.getLayouts( - guestGroup.getGroupId(), false, - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - - if (layouts.size() > 0) { - layout = layouts.get(0); - } - } - - return new Object[] {layout, layouts}; - } - - protected String getFriendlyURL(String friendlyURL) { - friendlyURL = GetterUtil.getString(friendlyURL); - - return FriendlyURLNormalizerUtil.normalize(friendlyURL); - } - - protected Object[] getViewableLayouts( - HttpServletRequest request, User user, - PermissionChecker permissionChecker, Layout layout, - List layouts) - throws PortalException, SystemException { - - if ((layouts == null) || layouts.isEmpty()) { - return new Object[] {layout, layouts}; - } - - Group group = layout.getGroup(); - - boolean hasViewLayoutPermission = false; - boolean hasViewStagingPermission = - (group.isStagingGroup() || group.isStagedRemotely()) && - GroupPermissionUtil.contains( - permissionChecker, group.getGroupId(), - ActionKeys.VIEW_STAGING); - - if (LayoutPermissionUtil.contains( - permissionChecker, layout, false, ActionKeys.VIEW) || - hasViewStagingPermission) { - - hasViewLayoutPermission = true; - } - - List accessibleLayouts = new ArrayList(); - - for (int i = 0; i < layouts.size(); i++) { - Layout curLayout = layouts.get(i); - - if (!curLayout.isHidden() && - (LayoutPermissionUtil.contains( - permissionChecker, curLayout, false, ActionKeys.VIEW) || - hasViewStagingPermission)) { - - if (accessibleLayouts.isEmpty() && !hasViewLayoutPermission) { - layout = curLayout; - } - - accessibleLayouts.add(curLayout); - } - } - - if (accessibleLayouts.isEmpty()) { - layouts = null; - - if (!hasViewLayoutPermission) { - SessionErrors.add( - request, LayoutPermissionException.class.getName()); - } - } - else { - layouts = accessibleLayouts; - } - - return new Object[] {layout, layouts}; - } - - protected Boolean hasPowerUserRole(User user) throws Exception { - return RoleLocalServiceUtil.hasUserRole( - user.getUserId(), user.getCompanyId(), RoleConstants.POWER_USER, - true); - } - - protected void initImportLARFiles() { - String privateLARFileName = - PropsValues.DEFAULT_USER_PRIVATE_LAYOUTS_LAR; - - if (_log.isDebugEnabled()) { - _log.debug("Reading private LAR file " + privateLARFileName); - } - - if (Validator.isNotNull(privateLARFileName)) { - privateLARFile = new File(privateLARFileName); - - if (!privateLARFile.exists()) { - _log.error( - "Private LAR file " + privateLARFile + " does not exist"); - - privateLARFile = null; - } - else { - if (_log.isDebugEnabled()) { - _log.debug("Using private LAR file " + privateLARFileName); - } - } - } - - String publicLARFileName = PropsValues.DEFAULT_USER_PUBLIC_LAYOUTS_LAR; - - if (_log.isDebugEnabled()) { - _log.debug("Reading public LAR file " + publicLARFileName); - } - - if (Validator.isNotNull(publicLARFileName)) { - publicLARFile = new File(publicLARFileName); - - if (!publicLARFile.exists()) { - _log.error( - "Public LAR file " + publicLARFile + " does not exist"); - - publicLARFile = null; - } - else { - if (_log.isDebugEnabled()) { - _log.debug("Using public LAR file " + publicLARFileName); - } - } - } - } - - protected boolean isLoginRequest(HttpServletRequest request) { - String requestURI = request.getRequestURI(); - - String mainPath = PortalUtil.getPathMain(); - - if (requestURI.startsWith(mainPath.concat("/portal/login"))) { - return true; - } - else { - return false; - } - } - - /** - * @deprecated - */ - protected boolean isViewableCommunity( - User user, long groupId, boolean privateLayout, - PermissionChecker permissionChecker) - throws PortalException, SystemException { - - return LayoutPermissionUtil.contains( - permissionChecker, groupId, privateLayout, 0, ActionKeys.VIEW); - } - - /** - * @deprecated - */ - protected boolean isViewableGroup( - User user, long groupId, boolean privateLayout, long layoutId, - String controlPanelCategory, PermissionChecker permissionChecker) - throws PortalException, SystemException { - - return LayoutPermissionUtil.contains( - permissionChecker, groupId, privateLayout, layoutId, - controlPanelCategory, ActionKeys.VIEW); - } - - protected List mergeAdditionalLayouts( - HttpServletRequest request, User user, - PermissionChecker permissionChecker, Layout layout, - List layouts) - throws PortalException, SystemException { - - if ((layout == null) || layout.isPrivateLayout()) { - return layouts; - } - - long layoutGroupId = layout.getGroupId(); - - Group guestGroup = GroupLocalServiceUtil.getGroup( - user.getCompanyId(), GroupConstants.GUEST); - - if (layoutGroupId != guestGroup.getGroupId()) { - Group layoutGroup = GroupLocalServiceUtil.getGroup(layoutGroupId); - - UnicodeProperties typeSettingsProperties = - layoutGroup.getTypeSettingsProperties(); - - boolean mergeGuestPublicPages = GetterUtil.getBoolean( - typeSettingsProperties.getProperty("mergeGuestPublicPages")); - - if (!mergeGuestPublicPages) { - return layouts; - } - - List guestLayouts = LayoutLocalServiceUtil.getLayouts( - guestGroup.getGroupId(), false, - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - - Object[] viewableLayouts = getViewableLayouts( - request, user, permissionChecker, layout, guestLayouts); - - guestLayouts = (List)viewableLayouts[1]; - - if (layouts == null) { - return guestLayouts; - } - - layouts.addAll(0, guestLayouts); - } - else { - HttpSession session = request.getSession(); - - Long previousGroupId = (Long)session.getAttribute( - WebKeys.VISITED_GROUP_ID_PREVIOUS); - - if ((previousGroupId != null) && - (previousGroupId.longValue() != layoutGroupId)) { - - Group previousGroup = null; - - try { - previousGroup = GroupLocalServiceUtil.getGroup( - previousGroupId.longValue()); - } - catch (NoSuchGroupException nsge) { - if (_log.isWarnEnabled()) { - _log.warn(nsge); - } - - return layouts; - } - - UnicodeProperties typeSettingsProperties = - previousGroup.getTypeSettingsProperties(); - - boolean mergeGuestPublicPages = GetterUtil.getBoolean( - typeSettingsProperties.getProperty( - "mergeGuestPublicPages")); - - if (!mergeGuestPublicPages) { - return layouts; - } - - List previousLayouts = - LayoutLocalServiceUtil.getLayouts( - previousGroupId.longValue(), false, - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - - Object[] viewableLayouts = getViewableLayouts( - request, user, permissionChecker, layout, previousLayouts); - - previousLayouts = (List)viewableLayouts[1]; - - if (previousLayouts != null) { - layouts.addAll(previousLayouts); - } - } - } - - return layouts; - } - - protected void rememberVisitedGroupIds( - HttpServletRequest request, long currentGroupId) { - - String requestURI = GetterUtil.getString(request.getRequestURI()); - - if (!requestURI.endsWith(_PATH_PORTAL_LAYOUT)) { - return; - } - - HttpSession session = request.getSession(); - - Long recentGroupId = (Long)session.getAttribute( - WebKeys.VISITED_GROUP_ID_RECENT); - - Long previousGroupId = (Long)session.getAttribute( - WebKeys.VISITED_GROUP_ID_PREVIOUS); - - if (recentGroupId == null) { - recentGroupId = new Long(currentGroupId); - - session.setAttribute( - WebKeys.VISITED_GROUP_ID_RECENT, recentGroupId); - } - else if (recentGroupId.longValue() != currentGroupId) { - previousGroupId = new Long(recentGroupId.longValue()); - - recentGroupId = new Long(currentGroupId); - - session.setAttribute( - WebKeys.VISITED_GROUP_ID_RECENT, recentGroupId); - - session.setAttribute( - WebKeys.VISITED_GROUP_ID_PREVIOUS, previousGroupId); - } - - if (_log.isDebugEnabled()) { - _log.debug("Current group id " + currentGroupId); - _log.debug("Recent group id " + recentGroupId); - _log.debug("Previous group id " + previousGroupId); - } - } - - protected void servicePre( - HttpServletRequest request, HttpServletResponse response) - throws Exception { - - ThemeDisplay themeDisplay = initThemeDisplay(request, response); - - if (themeDisplay == null) { - return; - } - - request.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay); - - // Service context - - ServiceContext serviceContext = ServiceContextFactory.getInstance( - request); - - ServiceContextThreadLocal.pushServiceContext(serviceContext); - - // Parallel render - - boolean parallelRenderEnable = true; - - Layout layout = themeDisplay.getLayout(); - - if (layout != null) { - LayoutTypePortlet layoutTypePortlet = - themeDisplay.getLayoutTypePortlet(); - - List portletIds = layoutTypePortlet.getPortletIds(); - - if (portletIds.size() == 1) { - String portletId = portletIds.get(0); - - Portlet portlet = PortletLocalServiceUtil.getPortletById( - portletId); - - if ((portlet != null) && !portlet.isAjaxable()) { - parallelRenderEnable = false; - } - } - } - - Boolean parallelRenderEnableObj = Boolean.valueOf(ParamUtil.getBoolean( - request, "p_p_parallel", parallelRenderEnable)); - - request.setAttribute( - WebKeys.PORTLET_PARALLEL_RENDER, parallelRenderEnableObj); - - // Main Journal article - - long mainJournalArticleId = ParamUtil.getLong(request, "p_j_a_id"); - - if (mainJournalArticleId > 0) { - try{ - JournalArticle mainJournalArticle = - JournalArticleServiceUtil.getArticle(mainJournalArticleId); - - AssetEntry layoutAssetEntry = - AssetEntryLocalServiceUtil.getEntry( - JournalArticle.class.getName(), - mainJournalArticle.getResourcePrimKey()); - - request.setAttribute( - WebKeys.LAYOUT_ASSET_ENTRY, layoutAssetEntry); - } - catch (NoSuchArticleException nsae) { - if (_log.isWarnEnabled()) { - _log.warn(nsae.getMessage()); - } - } - } - } - - protected void updateUserLayouts(User user) throws Exception { - Boolean hasPowerUserRole = null; - - // Private layouts - - boolean addDefaultUserPrivateLayouts = false; - - if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED && - PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_AUTO_CREATE) { - - addDefaultUserPrivateLayouts = true; - - if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) { - if (hasPowerUserRole == null) { - hasPowerUserRole = hasPowerUserRole(user); - } - - if (!hasPowerUserRole.booleanValue()) { - addDefaultUserPrivateLayouts = false; - } - } - } - - Boolean hasPrivateLayouts = null; - - if (addDefaultUserPrivateLayouts) { - hasPrivateLayouts = LayoutLocalServiceUtil.hasLayouts(user, true); - - if (!hasPrivateLayouts) { - addDefaultUserPrivateLayouts(user); - } - } - - boolean deleteDefaultUserPrivateLayouts = false; - - if (!PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED) { - deleteDefaultUserPrivateLayouts = true; - } - else if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) { - if (hasPowerUserRole == null) { - hasPowerUserRole = hasPowerUserRole(user); - } - - if (!hasPowerUserRole.booleanValue()) { - deleteDefaultUserPrivateLayouts = true; - } - } - - if (deleteDefaultUserPrivateLayouts) { - if (hasPrivateLayouts == null) { - hasPrivateLayouts = LayoutLocalServiceUtil.hasLayouts( - user, true); - } - - if (hasPrivateLayouts) { - deleteDefaultUserPrivateLayouts(user); - } - } - - // Public pages - - boolean addDefaultUserPublicLayouts = false; - - if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED && - PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_AUTO_CREATE) { - - addDefaultUserPublicLayouts = true; - - if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) { - if (hasPowerUserRole == null) { - hasPowerUserRole = hasPowerUserRole(user); - } - - if (!hasPowerUserRole.booleanValue()) { - addDefaultUserPublicLayouts = false; - } - } - } - - Boolean hasPublicLayouts = null; - - if (addDefaultUserPublicLayouts) { - hasPublicLayouts = LayoutLocalServiceUtil.hasLayouts(user, false); - - if (!hasPublicLayouts) { - addDefaultUserPublicLayouts(user); - } - } - - boolean deleteDefaultUserPublicLayouts = false; - - if (!PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) { - deleteDefaultUserPublicLayouts = true; - } - else if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) { - if (hasPowerUserRole == null) { - hasPowerUserRole = hasPowerUserRole(user); - } - - if (!hasPowerUserRole.booleanValue()) { - deleteDefaultUserPublicLayouts = true; - } - } - - if (deleteDefaultUserPublicLayouts) { - if (hasPublicLayouts == null) { - hasPublicLayouts = LayoutLocalServiceUtil.hasLayouts( - user, false); - } - - if (hasPublicLayouts) { - deleteDefaultUserPublicLayouts(user); - } - } - } - - protected File privateLARFile; - protected File publicLARFile; - - private static final String _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX = - "portlet_"; - - private static final String _PATH_PORTAL_LAYOUT = "/portal/layout"; - - private static Log _log = LogFactoryUtil.getLog(ServicePreAction.class); - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portal.events; + +import com.liferay.portal.LayoutPermissionException; +import com.liferay.portal.NoSuchGroupException; +import com.liferay.portal.NoSuchLayoutException; +import com.liferay.portal.NoSuchUserException; +import com.liferay.portal.kernel.dao.orm.QueryUtil; +import com.liferay.portal.kernel.events.Action; +import com.liferay.portal.kernel.events.ActionException; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.language.LanguageUtil; +import com.liferay.portal.kernel.lar.PortletDataHandlerKeys; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.portlet.LiferayPortletURL; +import com.liferay.portal.kernel.portlet.LiferayWindowState; +import com.liferay.portal.kernel.servlet.BrowserSnifferUtil; +import com.liferay.portal.kernel.servlet.HttpHeaders; +import com.liferay.portal.kernel.servlet.SessionErrors; +import com.liferay.portal.kernel.util.FriendlyURLNormalizerUtil; +import com.liferay.portal.kernel.util.GetterUtil; +import com.liferay.portal.kernel.util.HttpUtil; +import com.liferay.portal.kernel.util.LocaleUtil; +import com.liferay.portal.kernel.util.ParamUtil; +import com.liferay.portal.kernel.util.PropsKeys; +import com.liferay.portal.kernel.util.SessionParamUtil; +import com.liferay.portal.kernel.util.StringBundler; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.UnicodeProperties; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.model.ColorScheme; +import com.liferay.portal.model.Company; +import com.liferay.portal.model.Group; +import com.liferay.portal.model.GroupConstants; +import com.liferay.portal.model.Image; +import com.liferay.portal.model.Layout; +import com.liferay.portal.model.LayoutConstants; +import com.liferay.portal.model.LayoutSet; +import com.liferay.portal.model.LayoutTypePortlet; +import com.liferay.portal.model.LayoutTypePortletConstants; +import com.liferay.portal.model.Portlet; +import com.liferay.portal.model.RoleConstants; +import com.liferay.portal.model.Theme; +import com.liferay.portal.model.User; +import com.liferay.portal.model.impl.ColorSchemeImpl; +import com.liferay.portal.model.impl.VirtualLayout; +import com.liferay.portal.security.auth.PrincipalException; +import com.liferay.portal.security.permission.ActionKeys; +import com.liferay.portal.security.permission.PermissionChecker; +import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; +import com.liferay.portal.security.permission.PermissionThreadLocal; +import com.liferay.portal.service.GroupLocalServiceUtil; +import com.liferay.portal.service.ImageLocalServiceUtil; +import com.liferay.portal.service.LayoutLocalServiceUtil; +import com.liferay.portal.service.LayoutSetLocalServiceUtil; +import com.liferay.portal.service.PortletLocalServiceUtil; +import com.liferay.portal.service.RoleLocalServiceUtil; +import com.liferay.portal.service.ServiceContext; +import com.liferay.portal.service.ServiceContextFactory; +import com.liferay.portal.service.ServiceContextThreadLocal; +import com.liferay.portal.service.ThemeLocalServiceUtil; +import com.liferay.portal.service.UserLocalServiceUtil; +import com.liferay.portal.service.permission.GroupPermissionUtil; +import com.liferay.portal.service.permission.LayoutPermissionUtil; +import com.liferay.portal.service.permission.PortletPermissionUtil; +import com.liferay.portal.theme.ThemeDisplay; +import com.liferay.portal.theme.ThemeDisplayFactory; +import com.liferay.portal.util.CookieKeys; +import com.liferay.portal.util.LayoutClone; +import com.liferay.portal.util.LayoutCloneFactory; +import com.liferay.portal.util.PortalUtil; +import com.liferay.portal.util.PortletCategoryKeys; +import com.liferay.portal.util.PortletKeys; +import com.liferay.portal.util.PrefsPropsUtil; +import com.liferay.portal.util.PropsUtil; +import com.liferay.portal.util.PropsValues; +import com.liferay.portal.util.WebKeys; +import com.liferay.portal.webserver.WebServerServletTokenUtil; +import com.liferay.portlet.PortalPreferences; +import com.liferay.portlet.PortletPreferencesFactoryUtil; +import com.liferay.portlet.PortletURLImpl; +import com.liferay.portlet.asset.model.AssetEntry; +import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil; +import com.liferay.portlet.journal.NoSuchArticleException; +import com.liferay.portlet.journal.model.JournalArticle; +import com.liferay.portlet.journal.service.JournalArticleServiceUtil; +import com.liferay.portlet.sites.util.SitesUtil; + +import java.io.File; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.TimeZone; + +import javax.portlet.PortletMode; +import javax.portlet.PortletRequest; +import javax.portlet.PortletURL; +import javax.portlet.WindowState; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; + +import org.apache.commons.lang.time.StopWatch; +import org.apache.struts.Globals; + +/** + * @author Brian Wing Shun Chan + * @author Felix Ventero + * @author Jorge Ferrer + */ +public class ServicePreAction extends Action { + + public ServicePreAction() { + initImportLARFiles(); + } + + public ThemeDisplay initThemeDisplay( + HttpServletRequest request, HttpServletResponse response) + throws Exception { + + HttpSession session = request.getSession(); + + // Company + + Company company = PortalUtil.getCompany(request); + + long companyId = company.getCompanyId(); + + // CDN host + + String cdnHost = PortalUtil.getCDNHost(request); + + // Portal URL + + String portalURL = PortalUtil.getPortalURL(request); + + // Paths + + String contextPath = PortalUtil.getPathContext(); + String friendlyURLPrivateGroupPath = + PortalUtil.getPathFriendlyURLPrivateGroup(); + String friendlyURLPrivateUserPath = + PortalUtil.getPathFriendlyURLPrivateUser(); + String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic(); + String imagePath = cdnHost.concat(PortalUtil.getPathImage()); + String mainPath = PortalUtil.getPathMain(); + + String i18nPath = (String)request.getAttribute(WebKeys.I18N_PATH); + + if (Validator.isNotNull(i18nPath)) { + if (Validator.isNotNull(contextPath)) { + String i18nContextPath = contextPath.concat(i18nPath); + + friendlyURLPrivateGroupPath = StringUtil.replaceFirst( + friendlyURLPrivateGroupPath, contextPath, i18nContextPath); + friendlyURLPrivateUserPath = StringUtil.replaceFirst( + friendlyURLPrivateUserPath, contextPath, i18nContextPath); + friendlyURLPublicPath = StringUtil.replaceFirst( + friendlyURLPublicPath, contextPath, i18nContextPath); + mainPath = StringUtil.replaceFirst( + mainPath, contextPath, i18nContextPath); + } + else { + friendlyURLPrivateGroupPath = i18nPath.concat( + friendlyURLPrivateGroupPath); + friendlyURLPrivateUserPath = i18nPath.concat( + friendlyURLPrivateUserPath); + friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath); + mainPath = i18nPath.concat(mainPath); + } + } + + // Company logo + + StringBundler sb = new StringBundler(5); + + sb.append(imagePath); + sb.append("/company_logo?img_id="); + sb.append(company.getLogoId()); + sb.append("&t="); + sb.append(WebServerServletTokenUtil.getToken(company.getLogoId())); + + String companyLogo = sb.toString(); + + int companyLogoHeight = 0; + int companyLogoWidth = 0; + + Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo( + company.getLogoId()); + + if (companyLogoImage != null) { + companyLogoHeight = companyLogoImage.getHeight(); + companyLogoWidth = companyLogoImage.getWidth(); + } + + String realCompanyLogo = companyLogo; + int realCompanyLogoHeight = companyLogoHeight; + int realCompanyLogoWidth = companyLogoWidth; + + // User + + User user = null; + + try { + user = PortalUtil.getUser(request); + } + catch (NoSuchUserException nsue) { + if (_log.isWarnEnabled()) { + _log.warn(nsue.getMessage()); + } + + long userId = PortalUtil.getUserId(request); + + if (userId > 0) { + session.invalidate(); + } + + return null; + } + + boolean signedIn = false; + + if (user == null) { + user = company.getDefaultUser(); + } + else if (!user.isDefaultUser()) { + signedIn = true; + } + + if (PropsValues.BROWSER_CACHE_DISABLED || + (PropsValues.BROWSER_CACHE_SIGNED_IN_DISABLED && signedIn)) { + + response.setDateHeader(HttpHeaders.EXPIRES, 0); + response.setHeader( + HttpHeaders.CACHE_CONTROL, + HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE); + response.setHeader( + HttpHeaders.PRAGMA, HttpHeaders.PRAGMA_NO_CACHE_VALUE); + } + + User realUser = user; + + Long realUserId = (Long)session.getAttribute(WebKeys.USER_ID); + + if (realUserId != null) { + if (user.getUserId() != realUserId.longValue()) { + realUser = UserLocalServiceUtil.getUserById( + realUserId.longValue()); + } + } + + String doAsUserId = ParamUtil.getString(request, "doAsUserId"); + String doAsUserLanguageId = ParamUtil.getString( + request, "doAsUserLanguageId"); + long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId"); + + long refererPlid = ParamUtil.getLong(request, "refererPlid"); + + if (LayoutLocalServiceUtil.fetchLayout(refererPlid) == null) { + refererPlid = 0; + } + + String controlPanelCategory = ParamUtil.getString( + request, "controlPanelCategory"); + + // Permission checker + + PermissionChecker permissionChecker = + PermissionCheckerFactoryUtil.create(user, true); + + PermissionThreadLocal.setPermissionChecker(permissionChecker); + + // Locale + + Locale locale = (Locale)session.getAttribute(Globals.LOCALE_KEY); + + if (Validator.isNotNull(doAsUserLanguageId)) { + locale = LocaleUtil.fromLanguageId(doAsUserLanguageId); + } + + String i18nLanguageId = (String)request.getAttribute( + WebKeys.I18N_LANGUAGE_ID); + + if (Validator.isNotNull(i18nLanguageId)) { + locale = LocaleUtil.fromLanguageId(i18nLanguageId); + } + else if (locale == null) { + if (signedIn) { + locale = user.getLocale(); + } + else { + + // User previously set their preferred language + + String languageId = CookieKeys.getCookie( + request, CookieKeys.GUEST_LANGUAGE_ID, false); + + if (Validator.isNotNull(languageId)) { + locale = LocaleUtil.fromLanguageId(languageId); + } + + // Get locale from the request + + if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) { + locale = request.getLocale(); + } + + // Get locale from the default user + + if (locale == null) { + locale = user.getLocale(); + } + + if (Validator.isNull(locale.getCountry())) { + + // Locales must contain a country code + + locale = LanguageUtil.getLocale(locale.getLanguage()); + } + + if (!LanguageUtil.isAvailableLocale(locale)) { + locale = user.getLocale(); + } + } + + session.setAttribute(Globals.LOCALE_KEY, locale); + + LanguageUtil.updateCookie(request, response, locale); + } + + // Cookie support + + try { + + // LEP-4069 + + CookieKeys.validateSupportCookie(request); + } + catch (Exception e) { + CookieKeys.addSupportCookie(request, response); + } + + // Time zone + + TimeZone timeZone = user.getTimeZone(); + + if (timeZone == null) { + timeZone = company.getTimeZone(); + } + + // Layouts + + if (signedIn) { + updateUserLayouts(user); + } + + Layout layout = null; + List layouts = null; + + long plid = ParamUtil.getLong(request, "p_l_id"); + + if (plid > 0) { + layout = LayoutLocalServiceUtil.getLayout(plid); + + long sourceGroupId = ParamUtil.getLong(request, "p_v_l_s_g_id"); + + if ((sourceGroupId > 0) && (sourceGroupId != layout.getGroupId())) { + Group sourceGroup = GroupLocalServiceUtil.getGroup( + sourceGroupId); + + if (SitesUtil.isUserGroupLayoutSetViewable( + permissionChecker, layout.getGroup())) { + + layout = new VirtualLayout(layout, sourceGroup); + } + else { + layout = null; + } + } + } + else { + long groupId = ParamUtil.getLong(request, "groupId"); + boolean privateLayout = ParamUtil.getBoolean( + request, "privateLayout"); + long layoutId = ParamUtil.getLong(request, "layoutId"); + + if ((groupId > 0) && (layoutId > 0)) { + layout = LayoutLocalServiceUtil.getLayout( + groupId, privateLayout, layoutId); + } + } + + Boolean redirectToDefaultLayout = (Boolean)request.getAttribute( + WebKeys.REDIRECT_TO_DEFAULT_LAYOUT); + + if (redirectToDefaultLayout == null) { + redirectToDefaultLayout = Boolean.FALSE; + } + + if (layout != null) { + Group group = layout.getGroup(); + + if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) { + request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout); + } + + boolean isViewableGroup = LayoutPermissionUtil.contains( + permissionChecker, layout, controlPanelCategory, true, + ActionKeys.VIEW); + boolean isViewableStaging = GroupPermissionUtil.contains( + permissionChecker, group.getGroupId(), ActionKeys.VIEW_STAGING); + + if (isViewableStaging) { + layouts = LayoutLocalServiceUtil.getLayouts( + layout.getGroupId(), layout.isPrivateLayout(), + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + } + else if (!isViewableGroup && group.isStagingGroup()) { + layout = null; + } + else if (!isLoginRequest(request) && + (!isViewableGroup || + (!redirectToDefaultLayout && + !LayoutPermissionUtil.contains( + permissionChecker, layout, false, + ActionKeys.VIEW)))) { + + if (user.isDefaultUser() && + PropsValues.AUTH_LOGIN_PROMPT_ENABLED) { + + throw new PrincipalException("User is not authenticated"); + } + + sb = new StringBundler(6); + + sb.append("User "); + sb.append(user.getUserId()); + sb.append(" is not allowed to access the "); + sb.append(layout.isPrivateLayout() ? "private": "public"); + sb.append(" pages of group "); + sb.append(layout.getGroupId()); + + if (_log.isWarnEnabled()) { + _log.warn(sb.toString()); + } + + throw new NoSuchLayoutException(sb.toString()); + } + else if (isLoginRequest(request) && !isViewableGroup) { + layout = null; + } + else if (group.isLayoutPrototype()) { + layouts = new ArrayList(); + } + else { + layouts = LayoutLocalServiceUtil.getLayouts( + layout.getGroupId(), layout.isPrivateLayout(), + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + + if (!group.isControlPanel()) { + doAsGroupId = 0; + } + } + } + + List unfilteredLayouts = layouts; + + if (layout == null) { + Object[] defaultLayout = getDefaultLayout(request, user, signedIn); + + layout = (Layout)defaultLayout[0]; + layouts = (List)defaultLayout[1]; + + request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE); + } + + Object[] viewableLayouts = getViewableLayouts( + request, user, permissionChecker, layout, layouts); + + String layoutSetLogo = null; + + layout = (Layout)viewableLayouts[0]; + layouts = (List)viewableLayouts[1]; + + Group group = null; + + if (layout != null) { + group = layout.getGroup(); + + if (!group.isControlPanel()) { + rememberVisitedGroupIds(request, group.getGroupId()); + } + } + + LayoutTypePortlet layoutTypePortlet = null; + + layouts = mergeAdditionalLayouts( + request, user, permissionChecker, layout, layouts); + + LayoutSet layoutSet = null; + + boolean hasCustomizeLayoutPermission = false; + boolean hasUpdateLayoutPermission = false; + + boolean customizedView = SessionParamUtil.getBoolean( + request, "customized_view", true); + + if (layout != null) { + hasCustomizeLayoutPermission = LayoutPermissionUtil.contains( + permissionChecker, layout, ActionKeys.CUSTOMIZE); + hasUpdateLayoutPermission = LayoutPermissionUtil.contains( + permissionChecker, layout, ActionKeys.UPDATE); + + layoutSet = layout.getLayoutSet(); + + if (company.isSiteLogo()) { + long logoId = 0; + + if (layoutSet.isLogo()) { + logoId = layoutSet.getLogoId(); + + if (logoId == 0) { + logoId = layoutSet.getLiveLogoId(); + } + } + else { + LayoutSet siblingLayoutSet = + LayoutSetLocalServiceUtil.getLayoutSet( + layout.getGroupId(), !layout.isPrivateLayout()); + + if (siblingLayoutSet.isLogo()) { + logoId = siblingLayoutSet.getLogoId(); + } + } + + if (logoId > 0) { + sb = new StringBundler(5); + + sb.append(imagePath); + sb.append("/layout_set_logo?img_id="); + sb.append(logoId); + sb.append("&t="); + sb.append(WebServerServletTokenUtil.getToken(logoId)); + + layoutSetLogo = sb.toString(); + + Image layoutSetLogoImage = + ImageLocalServiceUtil.getCompanyLogo(logoId); + + companyLogo = layoutSetLogo; + companyLogoHeight = layoutSetLogoImage.getHeight(); + companyLogoWidth = layoutSetLogoImage.getWidth(); + } + } + + plid = layout.getPlid(); + + // Updates to shared layouts are not reflected until the next time + // the user logs in because group layouts are cached in the session + + layout = (Layout)layout.clone(); + + layoutTypePortlet = (LayoutTypePortlet)layout.getLayoutType(); + + boolean customizable = layoutTypePortlet.isCustomizable(); + + if (!customizable || + (group.isLayoutPrototype() || group.isLayoutSetPrototype())) { + + customizedView = false; + } + + layoutTypePortlet.setCustomizedView(customizedView); + layoutTypePortlet.setUpdatePermission(hasUpdateLayoutPermission); + + if (signedIn && customizable && customizedView && + hasCustomizeLayoutPermission) { + + PortalPreferences portalPreferences = + PortletPreferencesFactoryUtil.getPortalPreferences( + companyId, user.getUserId(), true); + + layoutTypePortlet.setPortalPreferences(portalPreferences); + } + + LayoutClone layoutClone = LayoutCloneFactory.getInstance(); + + if (layoutClone != null) { + String typeSettings = layoutClone.get(request, plid); + + if (typeSettings != null) { + UnicodeProperties typeSettingsProperties = + new UnicodeProperties(true); + + typeSettingsProperties.load(typeSettings); + + String stateMax = typeSettingsProperties.getProperty( + LayoutTypePortletConstants.STATE_MAX); + String stateMin = typeSettingsProperties.getProperty( + LayoutTypePortletConstants.STATE_MIN); + String modeAbout = typeSettingsProperties.getProperty( + LayoutTypePortletConstants.MODE_ABOUT); + String modeConfig = typeSettingsProperties.getProperty( + LayoutTypePortletConstants.MODE_CONFIG); + String modeEdit = typeSettingsProperties.getProperty( + LayoutTypePortletConstants.MODE_EDIT); + String modeEditDefaults = + typeSettingsProperties.getProperty( + LayoutTypePortletConstants.MODE_EDIT_DEFAULTS); + String modeEditGuest = typeSettingsProperties.getProperty( + LayoutTypePortletConstants.MODE_EDIT_GUEST); + String modeHelp = typeSettingsProperties.getProperty( + LayoutTypePortletConstants.MODE_HELP); + String modePreview = typeSettingsProperties.getProperty( + LayoutTypePortletConstants.MODE_PREVIEW); + String modePrint = typeSettingsProperties.getProperty( + LayoutTypePortletConstants.MODE_PRINT); + + layoutTypePortlet.setStateMax(stateMax); + layoutTypePortlet.setStateMin(stateMin); + layoutTypePortlet.setModeAbout(modeAbout); + layoutTypePortlet.setModeConfig(modeConfig); + layoutTypePortlet.setModeEdit(modeEdit); + layoutTypePortlet.setModeEditDefaults(modeEditDefaults); + layoutTypePortlet.setModeEditGuest(modeEditGuest); + layoutTypePortlet.setModeHelp(modeHelp); + layoutTypePortlet.setModePreview(modePreview); + layoutTypePortlet.setModePrint(modePrint); + } + } + + request.setAttribute(WebKeys.LAYOUT, layout); + request.setAttribute(WebKeys.LAYOUTS, layouts); + + if (layout.isPrivateLayout() || + !PropsValues.PERMISSIONS_LAYOUT_PUBLIC_CHECK_GUEST_ENABLED) { + + permissionChecker.setCheckGuest(false); + } + } + + // Scope + + long scopeGroupId = PortalUtil.getScopeGroupId(request); + long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId); + + // Theme and color scheme + + Theme theme = null; + ColorScheme colorScheme = null; + + boolean wapTheme = BrowserSnifferUtil.isWap(request); + + if ((layout != null) && group.isControlPanel()) { + String themeId = PrefsPropsUtil.getString( + companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID); + String colorSchemeId = + ColorSchemeImpl.getDefaultRegularColorSchemeId(); + + theme = ThemeLocalServiceUtil.getTheme( + companyId, themeId, wapTheme); + colorScheme = ThemeLocalServiceUtil.getColorScheme( + companyId, theme.getThemeId(), colorSchemeId, wapTheme); + + if (!wapTheme && theme.isWapTheme()) { + theme = ThemeLocalServiceUtil.getTheme( + companyId, + PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID, false); + colorScheme = ThemeLocalServiceUtil.getColorScheme( + companyId, theme.getThemeId(), colorSchemeId, false); + } + + request.setAttribute(WebKeys.THEME, theme); + request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme); + } + + boolean themeCssFastLoad = SessionParamUtil.getBoolean( + request, "css_fast_load", PropsValues.THEME_CSS_FAST_LOAD); + boolean themeImagesFastLoad = SessionParamUtil.getBoolean( + request, "images_fast_load", PropsValues.THEME_IMAGES_FAST_LOAD); + + boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED; + + if (themeJsBarebone) { + if (signedIn) { + themeJsBarebone = false; + } + } + + boolean themeJsFastLoad = SessionParamUtil.getBoolean( + request, "js_fast_load", PropsValues.JAVASCRIPT_FAST_LOAD); + + String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0"); + + lifecycle = ParamUtil.getString(request, "p_t_lifecycle", lifecycle); + + boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated"); + + String facebookCanvasPageURL = (String)request.getAttribute( + WebKeys.FACEBOOK_CANVAS_PAGE_URL); + + boolean widget = false; + + Boolean widgetObj = (Boolean)request.getAttribute(WebKeys.WIDGET); + + if (widgetObj != null) { + widget = widgetObj.booleanValue(); + } + + // Theme display + + ThemeDisplay themeDisplay = ThemeDisplayFactory.create(); + + // Set the CDN host, portal URL, and Facebook application ID first + // because other methods (setLookAndFeel) depend on them being set + + themeDisplay.setCDNHost(cdnHost); + themeDisplay.setPortalURL(portalURL); + themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL); + themeDisplay.setWidget(widget); + + themeDisplay.setCompany(company); + themeDisplay.setCompanyLogo(companyLogo); + themeDisplay.setCompanyLogoHeight(companyLogoHeight); + themeDisplay.setCompanyLogoWidth(companyLogoWidth); + themeDisplay.setRealCompanyLogo(realCompanyLogo); + themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight); + themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth); + themeDisplay.setUser(user); + themeDisplay.setRealUser(realUser); + themeDisplay.setDoAsUserId(doAsUserId); + themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId); + themeDisplay.setDoAsGroupId(doAsGroupId); + themeDisplay.setRefererPlid(refererPlid); + themeDisplay.setControlPanelCategory(controlPanelCategory); + themeDisplay.setLayoutSet(layoutSet); + themeDisplay.setLayoutSetLogo(layoutSetLogo); + themeDisplay.setLayout(layout); + themeDisplay.setLayouts(layouts); + themeDisplay.setUnfilteredLayouts(unfilteredLayouts); + themeDisplay.setPlid(plid); + themeDisplay.setLayoutTypePortlet(layoutTypePortlet); + themeDisplay.setScopeGroupId(scopeGroupId); + themeDisplay.setParentGroupId(parentGroupId); + themeDisplay.setSignedIn(signedIn); + themeDisplay.setPermissionChecker(permissionChecker); + themeDisplay.setLocale(locale); + themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale)); + themeDisplay.setI18nLanguageId(i18nLanguageId); + themeDisplay.setI18nPath(i18nPath); + themeDisplay.setTimeZone(timeZone); + themeDisplay.setLookAndFeel(theme, colorScheme); + themeDisplay.setThemeCssFastLoad(themeCssFastLoad); + themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad); + themeDisplay.setThemeJsBarebone(themeJsBarebone); + themeDisplay.setThemeJsFastLoad(themeJsFastLoad); + themeDisplay.setServerName(request.getServerName()); + themeDisplay.setServerPort(request.getServerPort()); + themeDisplay.setSecure(PortalUtil.isSecure(request)); + themeDisplay.setLifecycle(lifecycle); + themeDisplay.setLifecycleAction(lifecycle.equals("1")); + themeDisplay.setLifecycleRender(lifecycle.equals("0")); + themeDisplay.setLifecycleResource(lifecycle.equals("2")); + themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request)); + themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request)); + themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request)); + themeDisplay.setIsolated(isolated); + themeDisplay.setPathApplet(contextPath.concat("/applets")); + themeDisplay.setPathCms(contextPath.concat("/cms")); + themeDisplay.setPathContext(contextPath); + themeDisplay.setPathFlash(contextPath.concat("/flash")); + themeDisplay.setPathFriendlyURLPrivateGroup( + friendlyURLPrivateGroupPath); + themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath); + themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath); + themeDisplay.setPathImage(imagePath); + themeDisplay.setPathJavaScript( + cdnHost.concat(contextPath).concat("/html/js")); + themeDisplay.setPathMain(mainPath); + themeDisplay.setPathSound(contextPath.concat("/html/sound")); + + // Icons + + themeDisplay.setShowAddContentIcon(false); + themeDisplay.setShowControlPanelIcon(signedIn); + themeDisplay.setShowHomeIcon(true); + themeDisplay.setShowMyAccountIcon(signedIn); + themeDisplay.setShowPageSettingsIcon(false); + themeDisplay.setShowPortalIcon(true); + themeDisplay.setShowSignInIcon(!signedIn); + themeDisplay.setShowSignOutIcon(signedIn); + + boolean showSiteContentIcon = false; + + long controlPanelPlid = 0; + + if (signedIn) { + Group controlPanelGroup = GroupLocalServiceUtil.getGroup( + companyId, GroupConstants.CONTROL_PANEL); + + controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid( + controlPanelGroup.getGroupId(), true); + + List siteContentPortlets = + PortalUtil.getControlPanelPortlets( + PortletCategoryKeys.CONTENT, themeDisplay); + + Portlet groupPagesPortlet = PortletLocalServiceUtil.getPortletById( + PortletKeys.GROUP_PAGES); + + siteContentPortlets.remove(groupPagesPortlet); + + Portlet siteMembershipsAdminPortlet = + PortletLocalServiceUtil.getPortletById( + PortletKeys.SITE_MEMBERSHIPS_ADMIN); + + siteContentPortlets.remove(siteMembershipsAdminPortlet); + + Portlet siteSettingsPortlet = + PortletLocalServiceUtil.getPortletById( + PortletKeys.SITE_SETTINGS); + + siteContentPortlets.remove(siteSettingsPortlet); + + showSiteContentIcon = PortletPermissionUtil.contains( + permissionChecker, scopeGroupId, controlPanelPlid, + siteContentPortlets, ActionKeys.VIEW); + } + + themeDisplay.setShowSiteContentIcon(showSiteContentIcon); + + themeDisplay.setShowStagingIcon(false); + + // Session + + if (PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID && + !CookieKeys.hasSessionId(request)) { + + themeDisplay.setAddSessionIdToURL(true); + themeDisplay.setSessionId(session.getId()); + } + + // URLs + + String urlControlPanel = friendlyURLPrivateGroupPath.concat( + GroupConstants.CONTROL_PANEL_FRIENDLY_URL); + + if (Validator.isNotNull(doAsUserId)) { + urlControlPanel = HttpUtil.addParameter( + urlControlPanel, "doAsUserId", doAsUserId); + } + + if (scopeGroupId > 0) { + urlControlPanel = HttpUtil.addParameter( + urlControlPanel, "doAsGroupId", scopeGroupId); + } + + if (refererPlid > 0) { + urlControlPanel = HttpUtil.addParameter( + urlControlPanel, "refererPlid", refererPlid); + } + else if (plid > 0) { + urlControlPanel = HttpUtil.addParameter( + urlControlPanel, "refererPlid", plid); + } + + if (themeDisplay.isAddSessionIdToURL()) { + urlControlPanel = PortalUtil.getURLWithSessionId( + urlControlPanel, session.getId()); + } + + themeDisplay.setURLControlPanel(urlControlPanel); + + String siteContentURL = urlControlPanel; + + siteContentURL = HttpUtil.addParameter( + siteContentURL, "controlPanelCategory", + PortletCategoryKeys.CONTENT); + + themeDisplay.setURLSiteContent(siteContentURL); + + String currentURL = PortalUtil.getCurrentURL(request); + + themeDisplay.setURLCurrent(currentURL); + + String urlHome = PortalUtil.getHomeURL(request); + + themeDisplay.setURLHome(urlHome); + + if (layout != null) { + if (layout.isTypePortlet()) { + boolean freeformLayout = + layoutTypePortlet.getLayoutTemplateId().equals("freeform"); + + themeDisplay.setFreeformLayout(freeformLayout); + + if (hasUpdateLayoutPermission) { + themeDisplay.setShowAddContentIconPermission(true); + + if (!LiferayWindowState.isMaximized(request)) { + themeDisplay.setShowAddContentIcon(true); + } + + themeDisplay.setShowLayoutTemplatesIcon(true); + + if (!group.isUser()) { + themeDisplay.setShowPageCustomizationIcon(true); + } + + themeDisplay.setURLAddContent( + "Liferay.LayoutConfiguration.toggle('".concat( + PortletKeys.LAYOUT_CONFIGURATION).concat("');")); + + themeDisplay.setURLLayoutTemplates( + "Liferay.LayoutConfiguration.showTemplates();"); + } + + if (hasCustomizeLayoutPermission && customizedView) { + themeDisplay.setShowAddContentIconPermission(true); + + if (!LiferayWindowState.isMaximized(request)) { + themeDisplay.setShowAddContentIcon(true); + } + + themeDisplay.setURLAddContent( + "Liferay.LayoutConfiguration.toggle('".concat( + PortletKeys.LAYOUT_CONFIGURATION).concat("');")); + } + } + + if (hasUpdateLayoutPermission) { + themeDisplay.setShowPageSettingsIcon(true); + + LiferayPortletURL pageSettingsURL = new PortletURLImpl( + request, PortletKeys.LAYOUTS_ADMIN, controlPanelPlid, + PortletRequest.RENDER_PHASE); + + pageSettingsURL.setControlPanelCategory( + _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + + PortletKeys.LAYOUTS_ADMIN); + pageSettingsURL.setParameter( + "struts_action", "/layouts_admin/edit_layouts"); + + if (layout.isPrivateLayout()) { + pageSettingsURL.setParameter("tabs1", "private-pages"); + } + else { + pageSettingsURL.setParameter("tabs1", "public-pages"); + } + + pageSettingsURL.setParameter("closeRedirect", currentURL); + pageSettingsURL.setParameter( + "groupId", String.valueOf(scopeGroupId)); + pageSettingsURL.setParameter("selPlid", String.valueOf(plid)); + pageSettingsURL.setPortletMode(PortletMode.VIEW); + pageSettingsURL.setWindowState(LiferayWindowState.POP_UP); + + themeDisplay.setURLPageSettings(pageSettingsURL); + + boolean site = group.isSite(); + + if (!site && group.isStagingGroup()) { + Group liveGroup = group.getLiveGroup(); + + site = liveGroup.isSite(); + } + + if (site && + GroupPermissionUtil.contains( + permissionChecker, scopeGroupId, + ActionKeys.ASSIGN_MEMBERS)) { + + themeDisplay.setShowManageSiteMembershipsIcon(true); + + LiferayPortletURL manageSiteMembershipsURL = + new PortletURLImpl( + request, PortletKeys.SITE_MEMBERSHIPS_ADMIN, + controlPanelPlid, PortletRequest.RENDER_PHASE); + + manageSiteMembershipsURL.setControlPanelCategory( + _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + + PortletKeys.SITE_MEMBERSHIPS_ADMIN); + manageSiteMembershipsURL.setParameter( + "struts_action", "/sites_admin/edit_site_assignments"); + manageSiteMembershipsURL.setParameter( + "groupId", String.valueOf(scopeGroupId)); + manageSiteMembershipsURL.setParameter( + "selPlid", String.valueOf(plid)); + manageSiteMembershipsURL.setPortletMode(PortletMode.VIEW); + manageSiteMembershipsURL.setWindowState( + LiferayWindowState.POP_UP); + + themeDisplay.setURLManageSiteMemberships( + manageSiteMembershipsURL); + } + else { + themeDisplay.setShowManageSiteMembershipsIcon(false); + } + } + + boolean hasAddLayoutGroupPermission = GroupPermissionUtil.contains( + permissionChecker, scopeGroupId, ActionKeys.ADD_LAYOUT); + boolean hasAddLayoutLayoutPermission = + LayoutPermissionUtil.contains( + permissionChecker, layout, ActionKeys.ADD_LAYOUT); + boolean hasManageLayoutsGroupPermission = + GroupPermissionUtil.contains( + permissionChecker, scopeGroupId, ActionKeys.MANAGE_LAYOUTS); + boolean hasManageStagingPermission = GroupPermissionUtil.contains( + permissionChecker, scopeGroupId, ActionKeys.MANAGE_STAGING); + boolean hasPublishStagingPermission = GroupPermissionUtil.contains( + permissionChecker, scopeGroupId, ActionKeys.PUBLISH_STAGING); + boolean hasUpdateGroupPermission = GroupPermissionUtil.contains( + permissionChecker, scopeGroupId, ActionKeys.UPDATE); + boolean hasViewStagingPermission = GroupPermissionUtil.contains( + permissionChecker, scopeGroupId, ActionKeys.VIEW_STAGING); + + if (!group.isControlPanel() && !group.isUser() && + !group.isUserGroup() && hasUpdateGroupPermission) { + + themeDisplay.setShowSiteSettingsIcon(true); + + LiferayPortletURL siteSettingsURL = new PortletURLImpl( + request, PortletKeys.SITE_SETTINGS, controlPanelPlid, + PortletRequest.RENDER_PHASE); + + siteSettingsURL.setControlPanelCategory( + _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + + PortletKeys.SITE_SETTINGS); + siteSettingsURL.setParameter( + "struts_action", "/sites_admin/edit_site"); + siteSettingsURL.setParameter("closeRedirect", currentURL); + siteSettingsURL.setParameter( + "groupId", String.valueOf(scopeGroupId)); + siteSettingsURL.setPortletMode(PortletMode.VIEW); + siteSettingsURL.setWindowState(LiferayWindowState.POP_UP); + + themeDisplay.setURLSiteSettings(siteSettingsURL); + } + + if (!group.isLayoutPrototype() && + (hasAddLayoutGroupPermission || hasAddLayoutLayoutPermission || + hasManageLayoutsGroupPermission || hasUpdateGroupPermission)) { + + themeDisplay.setShowSiteMapSettingsIcon(true); + + LiferayPortletURL siteMapSettingsURL = new PortletURLImpl( + request, PortletKeys.LAYOUTS_ADMIN, controlPanelPlid, + PortletRequest.RENDER_PHASE); + + siteMapSettingsURL.setControlPanelCategory( + _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + + PortletKeys.LAYOUTS_ADMIN); + siteMapSettingsURL.setParameter( + "struts_action", "/layouts_admin/edit_layouts"); + + if (layout.isPrivateLayout()) { + siteMapSettingsURL.setParameter("tabs1", "private-pages"); + } + else { + siteMapSettingsURL.setParameter("tabs1", "public-pages"); + } + + siteMapSettingsURL.setParameter("closeRedirect", currentURL); + siteMapSettingsURL.setParameter( + "groupId", String.valueOf(scopeGroupId)); + siteMapSettingsURL.setParameter( + "selPlid", String.valueOf(plid)); + siteMapSettingsURL.setPortletMode(PortletMode.VIEW); + siteMapSettingsURL.setWindowState(LiferayWindowState.POP_UP); + + themeDisplay.setURLSiteMapSettings(siteMapSettingsURL); + } + + if (group.hasStagingGroup() && !group.isStagingGroup()) { + themeDisplay.setShowAddContentIcon(false); + themeDisplay.setShowLayoutTemplatesIcon(false); + themeDisplay.setShowPageSettingsIcon(false); + themeDisplay.setURLPublishToLive(null); + } + + if (group.isControlPanel()) { + themeDisplay.setShowPageSettingsIcon(false); + themeDisplay.setURLPublishToLive(null); + } + + // LEP-4987 + + if (group.isStaged() || group.isStagingGroup()) { + if (hasManageStagingPermission || hasPublishStagingPermission || + hasUpdateLayoutPermission || hasViewStagingPermission) { + + themeDisplay.setShowStagingIcon(true); + } + + if (hasPublishStagingPermission) { + PortletURL publishToLiveURL = new PortletURLImpl( + request, PortletKeys.LAYOUTS_ADMIN, plid, + PortletRequest.RENDER_PHASE); + + publishToLiveURL.setParameter( + "struts_action", "/layouts_admin/publish_layouts"); + + if (layout.isPrivateLayout()) { + publishToLiveURL.setParameter("tabs1", "private-pages"); + } + else { + publishToLiveURL.setParameter("tabs1", "public-pages"); + } + + publishToLiveURL.setParameter("pagesRedirect", currentURL); + publishToLiveURL.setParameter( + "groupId", String.valueOf(scopeGroupId)); + publishToLiveURL.setParameter( + "selPlid", String.valueOf(plid)); + publishToLiveURL.setPortletMode(PortletMode.VIEW); + publishToLiveURL.setWindowState( + LiferayWindowState.EXCLUSIVE); + + themeDisplay.setURLPublishToLive(publishToLiveURL); + } + } + + PortletURLImpl myAccountURL = new PortletURLImpl( + request, PortletKeys.MY_ACCOUNT, controlPanelPlid, + PortletRequest.RENDER_PHASE); + + if (scopeGroupId > 0) { + myAccountURL.setDoAsGroupId(scopeGroupId); + } + + myAccountURL.setParameter("struts_action", "/my_account/edit_user"); + myAccountURL.setPortletMode(PortletMode.VIEW); + + if (refererPlid > 0) { + myAccountURL.setRefererPlid(refererPlid); + } + else { + myAccountURL.setRefererPlid(plid); + } + + myAccountURL.setWindowState(WindowState.MAXIMIZED); + + themeDisplay.setURLMyAccount(myAccountURL); + } + + if ((!user.isActive()) || + (PrefsPropsUtil.getBoolean( + companyId, PropsKeys.TERMS_OF_USE_REQUIRED) && + !user.isAgreedToTermsOfUse())) { + + themeDisplay.setShowAddContentIcon(false); + themeDisplay.setShowMyAccountIcon(false); + themeDisplay.setShowPageSettingsIcon(false); + } + + if (group.isLayoutPrototype()) { + themeDisplay.setShowControlPanelIcon(false); + themeDisplay.setShowHomeIcon(false); + themeDisplay.setShowManageSiteMembershipsIcon(false); + themeDisplay.setShowMyAccountIcon(false); + themeDisplay.setShowPageCustomizationIcon(false); + themeDisplay.setShowPageSettingsIcon(true); + themeDisplay.setShowPortalIcon(false); + themeDisplay.setShowSignInIcon(false); + themeDisplay.setShowSignOutIcon(false); + themeDisplay.setShowSiteContentIcon(false); + themeDisplay.setShowSiteSettingsIcon(false); + themeDisplay.setShowStagingIcon(false); + } + + if (group.isLayoutSetPrototype()) { + themeDisplay.setShowPageCustomizationIcon(false); + themeDisplay.setShowSiteSettingsIcon(false); + } + + if (group.hasStagingGroup() && !group.isStagingGroup()) { + themeDisplay.setShowLayoutTemplatesIcon(false); + themeDisplay.setShowPageCustomizationIcon(false); + themeDisplay.setShowPageSettingsIcon(false); + themeDisplay.setShowSiteContentIcon(false); + themeDisplay.setShowSiteMapSettingsIcon(false); + themeDisplay.setShowSiteSettingsIcon(false); + } + + themeDisplay.setURLPortal(portalURL.concat(contextPath)); + + String urlSignIn = mainPath.concat("/portal/login"); + + if (layout != null) { + urlSignIn = HttpUtil.addParameter( + urlSignIn, "p_l_id", layout.getPlid()); + } + + themeDisplay.setURLSignIn(urlSignIn); + + themeDisplay.setURLSignOut(mainPath.concat("/portal/logout")); + + PortletURL updateManagerURL = new PortletURLImpl( + request, PortletKeys.UPDATE_MANAGER, plid, + PortletRequest.RENDER_PHASE); + + updateManagerURL.setParameter("struts_action", "/update_manager/view"); + updateManagerURL.setPortletMode(PortletMode.VIEW); + updateManagerURL.setWindowState(WindowState.MAXIMIZED); + + themeDisplay.setURLUpdateManager(updateManagerURL); + + return themeDisplay; + } + + @Override + public void run(HttpServletRequest request, HttpServletResponse response) + throws ActionException { + + StopWatch stopWatch = null; + + if (_log.isDebugEnabled()) { + stopWatch = new StopWatch(); + + stopWatch.start(); + } + + try { + servicePre(request, response); + } + catch (Exception e) { + throw new ActionException(e); + } + + if (_log.isDebugEnabled()) { + _log.debug("Running takes " + stopWatch.getTime() + " ms"); + } + } + + protected void addDefaultLayoutsByLAR( + long userId, long groupId, boolean privateLayout, File larFile) + throws PortalException, SystemException { + + Map parameterMap = new HashMap(); + + parameterMap.put( + PortletDataHandlerKeys.PERMISSIONS, + new String[] {Boolean.TRUE.toString()}); + parameterMap.put( + PortletDataHandlerKeys.PORTLET_DATA, + new String[] {Boolean.TRUE.toString()}); + parameterMap.put( + PortletDataHandlerKeys.PORTLET_DATA_CONTROL_DEFAULT, + new String[] {Boolean.TRUE.toString()}); + parameterMap.put( + PortletDataHandlerKeys.PORTLET_SETUP, + new String[] {Boolean.TRUE.toString()}); + parameterMap.put( + PortletDataHandlerKeys.USER_PERMISSIONS, + new String[] {Boolean.FALSE.toString()}); + + LayoutLocalServiceUtil.importLayouts( + userId, groupId, privateLayout, parameterMap, larFile); + } + + protected void addDefaultUserPrivateLayoutByProperties( + long userId, long groupId) + throws PortalException, SystemException { + + String friendlyURL = getFriendlyURL( + PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_FRIENDLY_URL); + + ServiceContext serviceContext = new ServiceContext(); + + Layout layout = LayoutLocalServiceUtil.addLayout( + userId, groupId, true, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID, + PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_NAME, StringPool.BLANK, + StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL, + serviceContext); + + LayoutTypePortlet layoutTypePortlet = + (LayoutTypePortlet)layout.getLayoutType(); + + layoutTypePortlet.setLayoutTemplateId( + 0, PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_TEMPLATE_ID, false); + + for (int i = 0; i < 10; i++) { + String columnId = "column-" + i; + String portletIds = PropsUtil.get( + PropsKeys.DEFAULT_USER_PRIVATE_LAYOUT_COLUMN + i); + + String[] portletIdsArray = StringUtil.split(portletIds); + + layoutTypePortlet.addPortletIds( + 0, portletIdsArray, columnId, false); + } + + LayoutLocalServiceUtil.updateLayout( + layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), + layout.getTypeSettings()); + + boolean updateLayoutSet = false; + + LayoutSet layoutSet = layout.getLayoutSet(); + + if (Validator.isNotNull( + PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_THEME_ID)) { + + layoutSet.setThemeId( + PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_THEME_ID); + + updateLayoutSet = true; + } + + if (Validator.isNotNull( + PropsValues. + DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_COLOR_SCHEME_ID)) { + + layoutSet.setColorSchemeId( + PropsValues. + DEFAULT_USER_PRIVATE_LAYOUT_REGULAR_COLOR_SCHEME_ID); + + updateLayoutSet = true; + } + + if (Validator.isNotNull( + PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_THEME_ID)) { + + layoutSet.setWapThemeId( + PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_THEME_ID); + + updateLayoutSet = true; + } + + if (Validator.isNotNull( + PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_COLOR_SCHEME_ID)) { + + layoutSet.setWapColorSchemeId( + PropsValues.DEFAULT_USER_PRIVATE_LAYOUT_WAP_COLOR_SCHEME_ID); + + updateLayoutSet = true; + } + + if (updateLayoutSet) { + LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet); + } + } + + protected void addDefaultUserPrivateLayouts(User user) + throws PortalException, SystemException { + + Group userGroup = user.getGroup(); + + if (privateLARFile != null) { + addDefaultLayoutsByLAR( + user.getUserId(), userGroup.getGroupId(), true, privateLARFile); + } + else { + addDefaultUserPrivateLayoutByProperties( + user.getUserId(), userGroup.getGroupId()); + } + } + + protected void addDefaultUserPublicLayoutByProperties( + long userId, long groupId) + throws PortalException, SystemException { + + String friendlyURL = getFriendlyURL( + PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_FRIENDLY_URL); + + ServiceContext serviceContext = new ServiceContext(); + + Layout layout = LayoutLocalServiceUtil.addLayout( + userId, groupId, false, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID, + PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_NAME, StringPool.BLANK, + StringPool.BLANK, LayoutConstants.TYPE_PORTLET, false, friendlyURL, + serviceContext); + + LayoutTypePortlet layoutTypePortlet = + (LayoutTypePortlet)layout.getLayoutType(); + + layoutTypePortlet.setLayoutTemplateId( + 0, PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_TEMPLATE_ID, false); + + for (int i = 0; i < 10; i++) { + String columnId = "column-" + i; + String portletIds = PropsUtil.get( + PropsKeys.DEFAULT_USER_PUBLIC_LAYOUT_COLUMN + i); + + String[] portletIdsArray = StringUtil.split(portletIds); + + layoutTypePortlet.addPortletIds( + 0, portletIdsArray, columnId, false); + } + + LayoutLocalServiceUtil.updateLayout( + layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), + layout.getTypeSettings()); + + boolean updateLayoutSet = false; + + LayoutSet layoutSet = layout.getLayoutSet(); + + if (Validator.isNotNull( + PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID)) { + + layoutSet.setThemeId( + PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_THEME_ID); + + updateLayoutSet = true; + } + + if (Validator.isNotNull( + PropsValues. + DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID)) { + + layoutSet.setColorSchemeId( + PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_REGULAR_COLOR_SCHEME_ID); + + updateLayoutSet = true; + } + + if (Validator.isNotNull( + PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID)) { + + layoutSet.setWapThemeId( + PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_THEME_ID); + + updateLayoutSet = true; + } + + if (Validator.isNotNull( + PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID)) { + + layoutSet.setWapColorSchemeId( + PropsValues.DEFAULT_USER_PUBLIC_LAYOUT_WAP_COLOR_SCHEME_ID); + + updateLayoutSet = true; + } + + if (updateLayoutSet) { + LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet); + } + } + + protected void addDefaultUserPublicLayouts(User user) + throws PortalException, SystemException { + + Group userGroup = user.getGroup(); + + if (publicLARFile != null) { + addDefaultLayoutsByLAR( + user.getUserId(), userGroup.getGroupId(), false, publicLARFile); + } + else { + addDefaultUserPublicLayoutByProperties( + user.getUserId(), userGroup.getGroupId()); + } + } + + protected void deleteDefaultUserPrivateLayouts(User user) + throws PortalException, SystemException { + + Group userGroup = user.getGroup(); + + ServiceContext serviceContext = new ServiceContext(); + + LayoutLocalServiceUtil.deleteLayouts( + userGroup.getGroupId(), true, serviceContext); + } + + protected void deleteDefaultUserPublicLayouts(User user) + throws PortalException, SystemException { + + Group userGroup = user.getGroup(); + + ServiceContext serviceContext = new ServiceContext(); + + LayoutLocalServiceUtil.deleteLayouts( + userGroup.getGroupId(), false, serviceContext); + } + + protected Object[] getDefaultLayout( + HttpServletRequest request, User user, boolean signedIn) + throws PortalException, SystemException { + + // Check the virtual host + + LayoutSet layoutSet = (LayoutSet)request.getAttribute( + WebKeys.VIRTUAL_HOST_LAYOUT_SET); + + if (layoutSet != null) { + List layouts = LayoutLocalServiceUtil.getLayouts( + layoutSet.getGroupId(), layoutSet.isPrivateLayout(), + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + + if (layouts.size() > 0) { + Layout layout = layouts.get(0); + + return new Object[] {layout, layouts}; + } + } + + Layout layout = null; + List layouts = null; + + if (signedIn) { + + // Check the user's personal layouts + + Group userGroup = user.getGroup(); + + layouts = LayoutLocalServiceUtil.getLayouts( + userGroup.getGroupId(), true, + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + + if (layouts.size() == 0) { + layouts = LayoutLocalServiceUtil.getLayouts( + userGroup.getGroupId(), false, + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + } + + if (layouts.size() > 0) { + layout = layouts.get(0); + } + + // Check the user's sites + + if (layout == null) { + LinkedHashMap groupParams = + new LinkedHashMap(); + + groupParams.put("usersGroups", new Long(user.getUserId())); + + List groups = GroupLocalServiceUtil.search( + user.getCompanyId(), null, null, groupParams, + QueryUtil.ALL_POS, QueryUtil.ALL_POS); + + for (Group group : groups) { + layouts = LayoutLocalServiceUtil.getLayouts( + group.getGroupId(), true, + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + + if (layouts.size() == 0) { + layouts = LayoutLocalServiceUtil.getLayouts( + group.getGroupId(), false, + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + } + + if (layouts.size() > 0) { + layout = layouts.get(0); + + break; + } + } + } + } + + if (layout == null) { + + // Check the Guest site + + Group guestGroup = GroupLocalServiceUtil.getGroup( + user.getCompanyId(), GroupConstants.GUEST); + + layouts = LayoutLocalServiceUtil.getLayouts( + guestGroup.getGroupId(), false, + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + + if (layouts.size() > 0) { + layout = layouts.get(0); + } + } + + return new Object[] {layout, layouts}; + } + + protected String getFriendlyURL(String friendlyURL) { + friendlyURL = GetterUtil.getString(friendlyURL); + + return FriendlyURLNormalizerUtil.normalize(friendlyURL); + } + + protected Object[] getViewableLayouts( + HttpServletRequest request, User user, + PermissionChecker permissionChecker, Layout layout, + List layouts) + throws PortalException, SystemException { + + if ((layouts == null) || layouts.isEmpty()) { + return new Object[] {layout, layouts}; + } + + Group group = layout.getGroup(); + + boolean hasViewLayoutPermission = false; + boolean hasViewStagingPermission = + (group.isStagingGroup() || group.isStagedRemotely()) && + GroupPermissionUtil.contains( + permissionChecker, group.getGroupId(), + ActionKeys.VIEW_STAGING); + + if (LayoutPermissionUtil.contains( + permissionChecker, layout, false, ActionKeys.VIEW) || + hasViewStagingPermission) { + + hasViewLayoutPermission = true; + } + + List accessibleLayouts = new ArrayList(); + + for (int i = 0; i < layouts.size(); i++) { + Layout curLayout = layouts.get(i); + + if (!curLayout.isHidden() && + (LayoutPermissionUtil.contains( + permissionChecker, curLayout, false, ActionKeys.VIEW) || + hasViewStagingPermission)) { + + if (accessibleLayouts.isEmpty() && !hasViewLayoutPermission) { + layout = curLayout; + } + + accessibleLayouts.add(curLayout); + } + } + + if (accessibleLayouts.isEmpty()) { + layouts = null; + + if (!hasViewLayoutPermission) { + SessionErrors.add( + request, LayoutPermissionException.class.getName()); + } + } + else { + layouts = accessibleLayouts; + } + + return new Object[] {layout, layouts}; + } + + protected Boolean hasPowerUserRole(User user) throws Exception { + return RoleLocalServiceUtil.hasUserRole( + user.getUserId(), user.getCompanyId(), RoleConstants.POWER_USER, + true); + } + + protected void initImportLARFiles() { + String privateLARFileName = + PropsValues.DEFAULT_USER_PRIVATE_LAYOUTS_LAR; + + if (_log.isDebugEnabled()) { + _log.debug("Reading private LAR file " + privateLARFileName); + } + + if (Validator.isNotNull(privateLARFileName)) { + privateLARFile = new File(privateLARFileName); + + if (!privateLARFile.exists()) { + _log.error( + "Private LAR file " + privateLARFile + " does not exist"); + + privateLARFile = null; + } + else { + if (_log.isDebugEnabled()) { + _log.debug("Using private LAR file " + privateLARFileName); + } + } + } + + String publicLARFileName = PropsValues.DEFAULT_USER_PUBLIC_LAYOUTS_LAR; + + if (_log.isDebugEnabled()) { + _log.debug("Reading public LAR file " + publicLARFileName); + } + + if (Validator.isNotNull(publicLARFileName)) { + publicLARFile = new File(publicLARFileName); + + if (!publicLARFile.exists()) { + _log.error( + "Public LAR file " + publicLARFile + " does not exist"); + + publicLARFile = null; + } + else { + if (_log.isDebugEnabled()) { + _log.debug("Using public LAR file " + publicLARFileName); + } + } + } + } + + protected boolean isLoginRequest(HttpServletRequest request) { + String requestURI = request.getRequestURI(); + + String mainPath = PortalUtil.getPathMain(); + + if (requestURI.startsWith(mainPath.concat("/portal/login"))) { + return true; + } + else { + return false; + } + } + + /** + * @deprecated + */ + protected boolean isViewableCommunity( + User user, long groupId, boolean privateLayout, + PermissionChecker permissionChecker) + throws PortalException, SystemException { + + return LayoutPermissionUtil.contains( + permissionChecker, groupId, privateLayout, 0, ActionKeys.VIEW); + } + + /** + * @deprecated + */ + protected boolean isViewableGroup( + User user, long groupId, boolean privateLayout, long layoutId, + String controlPanelCategory, PermissionChecker permissionChecker) + throws PortalException, SystemException { + + return LayoutPermissionUtil.contains( + permissionChecker, groupId, privateLayout, layoutId, + controlPanelCategory, ActionKeys.VIEW); + } + + protected List mergeAdditionalLayouts( + HttpServletRequest request, User user, + PermissionChecker permissionChecker, Layout layout, + List layouts) + throws PortalException, SystemException { + + if ((layout == null) || layout.isPrivateLayout()) { + return layouts; + } + + long layoutGroupId = layout.getGroupId(); + + Group guestGroup = GroupLocalServiceUtil.getGroup( + user.getCompanyId(), GroupConstants.GUEST); + + if (layoutGroupId != guestGroup.getGroupId()) { + Group layoutGroup = GroupLocalServiceUtil.getGroup(layoutGroupId); + + UnicodeProperties typeSettingsProperties = + layoutGroup.getTypeSettingsProperties(); + + boolean mergeGuestPublicPages = GetterUtil.getBoolean( + typeSettingsProperties.getProperty("mergeGuestPublicPages")); + + if (!mergeGuestPublicPages) { + return layouts; + } + + List guestLayouts = LayoutLocalServiceUtil.getLayouts( + guestGroup.getGroupId(), false, + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + + Object[] viewableLayouts = getViewableLayouts( + request, user, permissionChecker, layout, guestLayouts); + + guestLayouts = (List)viewableLayouts[1]; + + if (layouts == null) { + return guestLayouts; + } + + layouts.addAll(0, guestLayouts); + } + else { + HttpSession session = request.getSession(); + + Long previousGroupId = (Long)session.getAttribute( + WebKeys.VISITED_GROUP_ID_PREVIOUS); + + if ((previousGroupId != null) && + (previousGroupId.longValue() != layoutGroupId)) { + + Group previousGroup = null; + + try { + previousGroup = GroupLocalServiceUtil.getGroup( + previousGroupId.longValue()); + } + catch (NoSuchGroupException nsge) { + if (_log.isWarnEnabled()) { + _log.warn(nsge); + } + + return layouts; + } + + UnicodeProperties typeSettingsProperties = + previousGroup.getTypeSettingsProperties(); + + boolean mergeGuestPublicPages = GetterUtil.getBoolean( + typeSettingsProperties.getProperty( + "mergeGuestPublicPages")); + + if (!mergeGuestPublicPages) { + return layouts; + } + + List previousLayouts = + LayoutLocalServiceUtil.getLayouts( + previousGroupId.longValue(), false, + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + + Object[] viewableLayouts = getViewableLayouts( + request, user, permissionChecker, layout, previousLayouts); + + previousLayouts = (List)viewableLayouts[1]; + + if (previousLayouts != null) { + layouts.addAll(previousLayouts); + } + } + } + + return layouts; + } + + protected void rememberVisitedGroupIds( + HttpServletRequest request, long currentGroupId) { + + String requestURI = GetterUtil.getString(request.getRequestURI()); + + if (!requestURI.endsWith(_PATH_PORTAL_LAYOUT)) { + return; + } + + HttpSession session = request.getSession(); + + Long recentGroupId = (Long)session.getAttribute( + WebKeys.VISITED_GROUP_ID_RECENT); + + Long previousGroupId = (Long)session.getAttribute( + WebKeys.VISITED_GROUP_ID_PREVIOUS); + + if (recentGroupId == null) { + recentGroupId = new Long(currentGroupId); + + session.setAttribute( + WebKeys.VISITED_GROUP_ID_RECENT, recentGroupId); + } + else if (recentGroupId.longValue() != currentGroupId) { + previousGroupId = new Long(recentGroupId.longValue()); + + recentGroupId = new Long(currentGroupId); + + session.setAttribute( + WebKeys.VISITED_GROUP_ID_RECENT, recentGroupId); + + session.setAttribute( + WebKeys.VISITED_GROUP_ID_PREVIOUS, previousGroupId); + } + + if (_log.isDebugEnabled()) { + _log.debug("Current group id " + currentGroupId); + _log.debug("Recent group id " + recentGroupId); + _log.debug("Previous group id " + previousGroupId); + } + } + + protected void servicePre( + HttpServletRequest request, HttpServletResponse response) + throws Exception { + + ThemeDisplay themeDisplay = initThemeDisplay(request, response); + + if (themeDisplay == null) { + return; + } + + request.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay); + + // Service context + + ServiceContext serviceContext = ServiceContextFactory.getInstance( + request); + + ServiceContextThreadLocal.pushServiceContext(serviceContext); + + // Parallel render + + boolean parallelRenderEnable = true; + + Layout layout = themeDisplay.getLayout(); + + if (layout != null) { + LayoutTypePortlet layoutTypePortlet = + themeDisplay.getLayoutTypePortlet(); + + List portletIds = layoutTypePortlet.getPortletIds(); + + if (portletIds.size() == 1) { + String portletId = portletIds.get(0); + + Portlet portlet = PortletLocalServiceUtil.getPortletById( + portletId); + + if ((portlet != null) && !portlet.isAjaxable()) { + parallelRenderEnable = false; + } + } + } + + Boolean parallelRenderEnableObj = Boolean.valueOf(ParamUtil.getBoolean( + request, "p_p_parallel", parallelRenderEnable)); + + request.setAttribute( + WebKeys.PORTLET_PARALLEL_RENDER, parallelRenderEnableObj); + + // Main Journal article + + long mainJournalArticleId = ParamUtil.getLong(request, "p_j_a_id"); + + if (mainJournalArticleId > 0) { + try{ + JournalArticle mainJournalArticle = + JournalArticleServiceUtil.getArticle(mainJournalArticleId); + + AssetEntry layoutAssetEntry = + AssetEntryLocalServiceUtil.getEntry( + JournalArticle.class.getName(), + mainJournalArticle.getResourcePrimKey()); + + request.setAttribute( + WebKeys.LAYOUT_ASSET_ENTRY, layoutAssetEntry); + } + catch (NoSuchArticleException nsae) { + if (_log.isWarnEnabled()) { + _log.warn(nsae.getMessage()); + } + } + } + } + + protected void updateUserLayouts(User user) throws Exception { + Boolean hasPowerUserRole = null; + + // Private layouts + + boolean addDefaultUserPrivateLayouts = false; + + if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED && + PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_AUTO_CREATE) { + + addDefaultUserPrivateLayouts = true; + + if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) { + if (hasPowerUserRole == null) { + hasPowerUserRole = hasPowerUserRole(user); + } + + if (!hasPowerUserRole.booleanValue()) { + addDefaultUserPrivateLayouts = false; + } + } + } + + Boolean hasPrivateLayouts = null; + + if (addDefaultUserPrivateLayouts) { + hasPrivateLayouts = LayoutLocalServiceUtil.hasLayouts(user, true); + + if (!hasPrivateLayouts) { + addDefaultUserPrivateLayouts(user); + } + } + + boolean deleteDefaultUserPrivateLayouts = false; + + if (!PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED) { + deleteDefaultUserPrivateLayouts = true; + } + else if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_POWER_USER_REQUIRED) { + if (hasPowerUserRole == null) { + hasPowerUserRole = hasPowerUserRole(user); + } + + if (!hasPowerUserRole.booleanValue()) { + deleteDefaultUserPrivateLayouts = true; + } + } + + if (deleteDefaultUserPrivateLayouts) { + if (hasPrivateLayouts == null) { + hasPrivateLayouts = LayoutLocalServiceUtil.hasLayouts( + user, true); + } + + if (hasPrivateLayouts) { + deleteDefaultUserPrivateLayouts(user); + } + } + + // Public pages + + boolean addDefaultUserPublicLayouts = false; + + if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED && + PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_AUTO_CREATE) { + + addDefaultUserPublicLayouts = true; + + if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) { + if (hasPowerUserRole == null) { + hasPowerUserRole = hasPowerUserRole(user); + } + + if (!hasPowerUserRole.booleanValue()) { + addDefaultUserPublicLayouts = false; + } + } + } + + Boolean hasPublicLayouts = null; + + if (addDefaultUserPublicLayouts) { + hasPublicLayouts = LayoutLocalServiceUtil.hasLayouts(user, false); + + if (!hasPublicLayouts) { + addDefaultUserPublicLayouts(user); + } + } + + boolean deleteDefaultUserPublicLayouts = false; + + if (!PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) { + deleteDefaultUserPublicLayouts = true; + } + else if (PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_POWER_USER_REQUIRED) { + if (hasPowerUserRole == null) { + hasPowerUserRole = hasPowerUserRole(user); + } + + if (!hasPowerUserRole.booleanValue()) { + deleteDefaultUserPublicLayouts = true; + } + } + + if (deleteDefaultUserPublicLayouts) { + if (hasPublicLayouts == null) { + hasPublicLayouts = LayoutLocalServiceUtil.hasLayouts( + user, false); + } + + if (hasPublicLayouts) { + deleteDefaultUserPublicLayouts(user); + } + } + } + + protected File privateLARFile; + protected File publicLARFile; + + private static final String _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX = + "portlet_"; + + private static final String _PATH_PORTAL_LAYOUT = "/portal/layout"; + + private static Log _log = LogFactoryUtil.getLog(ServicePreAction.class); + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portal/facebook/FacebookServlet.java b/portal-impl/src/com/liferay/portal/facebook/FacebookServlet.java index 7a4ea73abfc23e..2a78e573b9f7ad 100644 --- a/portal-impl/src/com/liferay/portal/facebook/FacebookServlet.java +++ b/portal-impl/src/com/liferay/portal/facebook/FacebookServlet.java @@ -1,109 +1,107 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portal.facebook; - -import com.liferay.portal.NoSuchLayoutException; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.servlet.ServletResponseUtil; -import com.liferay.portal.kernel.servlet.StringServletResponse; -import com.liferay.portal.kernel.util.StringPool; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.servlet.filters.gzip.GZipFilter; -import com.liferay.portal.util.PortalUtil; -import com.liferay.portal.util.WebKeys; -import com.liferay.portlet.social.util.FacebookUtil; - -import java.io.IOException; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Brian Wing Shun Chan - */ -public class FacebookServlet extends HttpServlet { - - @Override - public void service( - HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException { - - try { - String[] facebookData = FacebookUtil.getFacebookData(request); - - if ((facebookData == null) || - !PortalUtil.isValidResourceId(facebookData[1])) { - - PortalUtil.sendError( - HttpServletResponse.SC_NOT_FOUND, - new NoSuchLayoutException(), request, response); - } - else { - String facebookCanvasPageURL = facebookData[0]; - String redirect = facebookData[1]; - - request.setAttribute( - WebKeys.FACEBOOK_CANVAS_PAGE_URL, facebookCanvasPageURL); - request.setAttribute(GZipFilter.SKIP_FILTER, Boolean.TRUE); - - ServletContext servletContext = getServletContext(); - - RequestDispatcher requestDispatcher = - servletContext.getRequestDispatcher(redirect); - - StringServletResponse stringResponse = - new StringServletResponse(response); - - requestDispatcher.forward(request, stringResponse); - - String fbml = stringResponse.getString(); - - fbml = fixFbml(fbml); - - ServletResponseUtil.write(response, fbml); - } - } - catch (Exception e) { - _log.error(e, e); - - PortalUtil.sendError( - HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e, request, - response); - } - } - - protected String fixFbml(String fbml) { - fbml = StringUtil.replace( - fbml, - new String[] { - "", - "" - }, - new String[] { - StringPool.BLANK, - StringPool.BLANK - }); - - return fbml; - } - - private static Log _log = LogFactoryUtil.getLog(FacebookServlet.class); - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portal.facebook; + +import com.liferay.portal.NoSuchLayoutException; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.servlet.ServletResponseUtil; +import com.liferay.portal.kernel.servlet.StringServletResponse; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.servlet.filters.gzip.GZipFilter; +import com.liferay.portal.util.PortalUtil; +import com.liferay.portal.util.WebKeys; +import com.liferay.portlet.social.util.FacebookUtil; + +import java.io.IOException; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author Brian Wing Shun Chan + */ +public class FacebookServlet extends HttpServlet { + + @Override + public void service( + HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + + try { + String[] facebookData = FacebookUtil.getFacebookData(request); + + if ((facebookData == null) || + !PortalUtil.isValidResourceId(facebookData[1])) { + + PortalUtil.sendError( + HttpServletResponse.SC_NOT_FOUND, + new NoSuchLayoutException(), request, response); + } + else { + String facebookCanvasPageURL = facebookData[0]; + String redirect = facebookData[1]; + + request.setAttribute( + WebKeys.FACEBOOK_CANVAS_PAGE_URL, facebookCanvasPageURL); + request.setAttribute(GZipFilter.SKIP_FILTER, Boolean.TRUE); + + ServletContext servletContext = getServletContext(); + + RequestDispatcher requestDispatcher = + servletContext.getRequestDispatcher(redirect); + + StringServletResponse stringResponse = + new StringServletResponse(response); + + requestDispatcher.forward(request, stringResponse); + + String fbml = stringResponse.getString(); + + fbml = fixFbml(fbml); + + ServletResponseUtil.write(response, fbml); + } + } + catch (Exception e) { + _log.error(e, e); + + PortalUtil.sendError( + HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e, request, + response); + } + } + + protected String fixFbml(String fbml) { + fbml = StringUtil.replace( + fbml, + new String[] { + "", "" + }, + new String[] { + StringPool.BLANK, StringPool.BLANK + }); + + return fbml; + } + + private static Log _log = LogFactoryUtil.getLog(FacebookServlet.class); + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portal/freemarker/FreeMarkerVariablesImpl.java b/portal-impl/src/com/liferay/portal/freemarker/FreeMarkerVariablesImpl.java index cf0cbbb99f8443..d2d443f23c97f5 100644 --- a/portal-impl/src/com/liferay/portal/freemarker/FreeMarkerVariablesImpl.java +++ b/portal-impl/src/com/liferay/portal/freemarker/FreeMarkerVariablesImpl.java @@ -235,8 +235,7 @@ public void insertHelperUtilities( UtilLocator utilLocator = UtilLocator.getInstance(); freeMarkerContext.put( - "saxReaderUtil", - utilLocator.findUtil(SAXReader.class.getName())); + "saxReaderUtil", utilLocator.findUtil(SAXReader.class.getName())); // Service locator @@ -258,8 +257,7 @@ public void insertHelperUtilities( // Static class util freeMarkerContext.put( - "staticUtil", - BeansWrapper.getDefaultInstance().getStaticModels()); + "staticUtil", BeansWrapper.getDefaultInstance().getStaticModels()); // String util diff --git a/portal-impl/src/com/liferay/portal/language/LanguageResources.java b/portal-impl/src/com/liferay/portal/language/LanguageResources.java index d87980c011e4c8..26dc2f548b1771 100644 --- a/portal-impl/src/com/liferay/portal/language/LanguageResources.java +++ b/portal-impl/src/com/liferay/portal/language/LanguageResources.java @@ -49,8 +49,7 @@ public static String fixValue(String value) { if (value.endsWith(LangBuilder.AUTOMATIC_TRANSLATION)) { value = value.substring( - 0, - value.length() - LangBuilder.AUTOMATIC_TRANSLATION.length()); + 0, value.length() - LangBuilder.AUTOMATIC_TRANSLATION.length()); } return value; diff --git a/portal-impl/src/com/liferay/portal/lar/LayoutExporter.java b/portal-impl/src/com/liferay/portal/lar/LayoutExporter.java index a2333f8ddd1171..801c7ea4a16701 100644 --- a/portal-impl/src/com/liferay/portal/lar/LayoutExporter.java +++ b/portal-impl/src/com/liferay/portal/lar/LayoutExporter.java @@ -598,8 +598,7 @@ protected void exportJournalArticle( try { article = JournalArticleLocalServiceUtil.getLatestArticle( - articleGroupId, articleId, - WorkflowConstants.STATUS_APPROVED); + articleGroupId, articleId, WorkflowConstants.STATUS_APPROVED); } catch (NoSuchArticleException nsae) { if (_log.isWarnEnabled()) { diff --git a/portal-impl/src/com/liferay/portal/lar/LayoutImporter.java b/portal-impl/src/com/liferay/portal/lar/LayoutImporter.java index 11a4654d9ea859..5f7f4503abd7d7 100644 --- a/portal-impl/src/com/liferay/portal/lar/LayoutImporter.java +++ b/portal-impl/src/com/liferay/portal/lar/LayoutImporter.java @@ -521,8 +521,8 @@ protected void doImportLayouts( newLayouts, newLayoutsMap, newLayoutIds, portletsMergeMode, themeId, colorSchemeId, layoutsImportMode, privateLayout, importPermissions, importPublicLayoutPermissions, - importUserPermissions, importThemeSettings, - rootElement, layoutElement); + importUserPermissions, importThemeSettings, rootElement, + layoutElement); } Element portletsElement = rootElement.element("portlets"); @@ -1022,8 +1022,8 @@ else if (layoutsImportMode.equals( newLayouts, newLayoutsMap, newLayoutIds, portletsMergeMode, themeId, colorSchemeId, layoutsImportMode, privateLayout, importPermissions, importPublicLayoutPermissions, - importUserPermissions, importThemeSettings, - rootElement, (Element)parentLayoutNode); + importUserPermissions, importThemeSettings, rootElement, + (Element)parentLayoutNode); Layout parentLayout = newLayoutsMap.get(parentLayoutId); diff --git a/portal-impl/src/com/liferay/portal/lar/PermissionImporter.java b/portal-impl/src/com/liferay/portal/lar/PermissionImporter.java index 179184c13e9617..b8b7f810d57504 100644 --- a/portal-impl/src/com/liferay/portal/lar/PermissionImporter.java +++ b/portal-impl/src/com/liferay/portal/lar/PermissionImporter.java @@ -100,8 +100,7 @@ protected void importGroupPermissions( protected void importGroupRoles( LayoutCache layoutCache, long companyId, long groupId, - String resourceName, String entityName, - Element parentElement) + String resourceName, String entityName, Element parentElement) throws Exception { Element entityRolesElement = parentElement.element( @@ -586,8 +585,8 @@ protected void importPortletRoles( layoutCache, companyId, groupId, resourceName, rolesElement); importInheritedRoles( - layoutCache, companyId, groupId, resourceName, - "organization", rolesElement); + layoutCache, companyId, groupId, resourceName, "organization", + rolesElement); importInheritedRoles( layoutCache, companyId, groupId, resourceName, "user-group", diff --git a/portal-impl/src/com/liferay/portal/lar/PortletImporter.java b/portal-impl/src/com/liferay/portal/lar/PortletImporter.java index bd0b1da2c8ae6a..414a13e009245c 100644 --- a/portal-impl/src/com/liferay/portal/lar/PortletImporter.java +++ b/portal-impl/src/com/liferay/portal/lar/PortletImporter.java @@ -1,1603 +1,1601 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portal.lar; - -import com.liferay.portal.LARFileException; -import com.liferay.portal.LARTypeException; -import com.liferay.portal.LayoutImportException; -import com.liferay.portal.NoSuchLayoutException; -import com.liferay.portal.PortletIdException; -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.lar.ImportExportThreadLocal; -import com.liferay.portal.kernel.lar.PortletDataContext; -import com.liferay.portal.kernel.lar.PortletDataHandler; -import com.liferay.portal.kernel.lar.PortletDataHandlerKeys; -import com.liferay.portal.kernel.lar.UserIdStrategy; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.search.Indexer; -import com.liferay.portal.kernel.search.IndexerRegistryUtil; -import com.liferay.portal.kernel.util.ArrayUtil; -import com.liferay.portal.kernel.util.GetterUtil; -import com.liferay.portal.kernel.util.LocaleUtil; -import com.liferay.portal.kernel.util.MapUtil; -import com.liferay.portal.kernel.util.ReleaseInfo; -import com.liferay.portal.kernel.util.StringBundler; -import com.liferay.portal.kernel.util.StringPool; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.kernel.xml.Document; -import com.liferay.portal.kernel.xml.DocumentException; -import com.liferay.portal.kernel.xml.Element; -import com.liferay.portal.kernel.xml.Node; -import com.liferay.portal.kernel.xml.SAXReaderUtil; -import com.liferay.portal.kernel.zip.ZipReader; -import com.liferay.portal.kernel.zip.ZipReaderFactoryUtil; -import com.liferay.portal.model.Group; -import com.liferay.portal.model.Layout; -import com.liferay.portal.model.Lock; -import com.liferay.portal.model.Portlet; -import com.liferay.portal.model.PortletConstants; -import com.liferay.portal.model.PortletItem; -import com.liferay.portal.model.PortletPreferences; -import com.liferay.portal.model.User; -import com.liferay.portal.security.permission.PermissionCacheUtil; -import com.liferay.portal.service.GroupLocalServiceUtil; -import com.liferay.portal.service.LayoutLocalServiceUtil; -import com.liferay.portal.service.PortletItemLocalServiceUtil; -import com.liferay.portal.service.PortletLocalServiceUtil; -import com.liferay.portal.service.PortletPreferencesLocalServiceUtil; -import com.liferay.portal.service.ServiceContext; -import com.liferay.portal.service.UserLocalServiceUtil; -import com.liferay.portal.service.persistence.PortletPreferencesUtil; -import com.liferay.portal.service.persistence.UserUtil; -import com.liferay.portal.servlet.filters.cache.CacheUtil; -import com.liferay.portal.util.PortletKeys; -import com.liferay.portal.util.PropsValues; -import com.liferay.portlet.PortletPreferencesFactoryUtil; -import com.liferay.portlet.PortletPreferencesImpl; -import com.liferay.portlet.asset.NoSuchCategoryException; -import com.liferay.portlet.asset.NoSuchEntryException; -import com.liferay.portlet.asset.NoSuchTagException; -import com.liferay.portlet.asset.model.AssetCategory; -import com.liferay.portlet.asset.model.AssetCategoryConstants; -import com.liferay.portlet.asset.model.AssetEntry; -import com.liferay.portlet.asset.model.AssetTag; -import com.liferay.portlet.asset.model.AssetVocabulary; -import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil; -import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil; -import com.liferay.portlet.asset.service.AssetLinkLocalServiceUtil; -import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil; -import com.liferay.portlet.asset.service.AssetVocabularyLocalServiceUtil; -import com.liferay.portlet.asset.service.persistence.AssetCategoryUtil; -import com.liferay.portlet.asset.service.persistence.AssetTagUtil; -import com.liferay.portlet.asset.service.persistence.AssetVocabularyUtil; -import com.liferay.portlet.expando.NoSuchTableException; -import com.liferay.portlet.expando.model.ExpandoColumn; -import com.liferay.portlet.expando.model.ExpandoTable; -import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil; -import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil; -import com.liferay.portlet.expando.util.ExpandoConverterUtil; -import com.liferay.portlet.journalcontent.util.JournalContentUtil; -import com.liferay.portlet.messageboards.model.MBMessage; -import com.liferay.portlet.ratings.model.RatingsEntry; - -import java.io.File; -import java.io.Serializable; - -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.commons.lang.time.StopWatch; - -/** - * @author Brian Wing Shun Chan - * @author Joel Kozikowski - * @author Charles May - * @author Raymond Augé - * @author Jorge Ferrer - * @author Bruno Farache - * @author Zsigmond Rab - * @author Douglas Wong - */ -public class PortletImporter { - - public void importPortletInfo( - long userId, long plid, long groupId, String portletId, - Map parameterMap, File file) - throws Exception { - - try { - ImportExportThreadLocal.setPortletImportInProcess(true); - - doImportPortletInfo( - userId, plid, groupId, portletId, parameterMap, file); - } - finally { - ImportExportThreadLocal.setPortletImportInProcess(false); - - CacheUtil.clearCache(); - JournalContentUtil.clearCache(); - PermissionCacheUtil.clearCache(); - } - } - - protected String checkPortletPreferences( - PortletDataContext portletDataContext, long companyId, - long ownerId, int ownerType, long plid, String portletId, - String xml) - throws Exception { - - String rootPotletId = PortletConstants.getRootPortletId(portletId); - - if (!rootPotletId.equals(PortletKeys.ASSET_PUBLISHER)) { - return xml; - } - - PortletPreferencesImpl portletPreferences = - (PortletPreferencesImpl)PortletPreferencesFactoryUtil. - fromXML(companyId, ownerId, ownerType, plid, portletId, xml); - - Enumeration enu = portletPreferences.getNames(); - - while (enu.hasMoreElements()) { - String name = enu.nextElement(); - - String value = GetterUtil.getString( - portletPreferences.getValue(name, StringPool.BLANK)); - - String prefix = "queryName"; - - if (value.equalsIgnoreCase("assetCategories") && - name.startsWith(prefix)) { - - String index = name.substring(prefix.length(), name.length()); - - String queryValuesName = "queryValues" + index; - - String[] importedAssetCategoryPKs = - portletPreferences.getValues(queryValuesName, null); - - Map assetCategoryPKs = - (Map)portletDataContext.getNewPrimaryKeysMap( - AssetCategory.class); - - String[] newAssetCategoryPKs = new String[ - importedAssetCategoryPKs.length]; - - int i = 0; - - for (String importedAssetCategoryPK : - importedAssetCategoryPKs) { - - String newAssetCategoryPK = StringUtil.valueOf( - assetCategoryPKs.get( - new Long(importedAssetCategoryPK))); - - if (Validator.isNull(newAssetCategoryPK)) { - newAssetCategoryPK = importedAssetCategoryPK; - } - - newAssetCategoryPKs[i++] = newAssetCategoryPK; - } - - portletPreferences.setValues( - queryValuesName, newAssetCategoryPKs); - } - } - - return PortletPreferencesFactoryUtil.toXML(portletPreferences); - } - - protected void deletePortletData( - PortletDataContext portletDataContext, String portletId, long plid) - throws Exception { - - long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT; - int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT; - - PortletPreferences portletPreferences = - PortletPreferencesUtil.fetchByO_O_P_P( - ownerId, ownerType, plid, portletId); - - if (portletPreferences == null) { - portletPreferences = - new com.liferay.portal.model.impl.PortletPreferencesImpl(); - } - - String xml = deletePortletData( - portletDataContext, portletId, portletPreferences); - - if (xml != null) { - PortletPreferencesLocalServiceUtil.updatePreferences( - ownerId, ownerType, plid, portletId, xml); - } - } - - protected String deletePortletData( - PortletDataContext portletDataContext, String portletId, - PortletPreferences portletPreferences) - throws Exception { - - Portlet portlet = PortletLocalServiceUtil.getPortletById( - portletDataContext.getCompanyId(), portletId); - - if (portlet == null) { - if (_log.isDebugEnabled()) { - _log.debug( - "Do not delete portlet data for " + portletId + - " because the portlet does not exist"); - } - - return null; - } - - PortletDataHandler portletDataHandler = - portlet.getPortletDataHandlerInstance(); - - if (portletDataHandler == null) { - if (_log.isDebugEnabled()) { - _log.debug( - "Do not delete portlet data for " + portletId + - " because the portlet does not have a " + - "PortletDataHandler"); - } - - return null; - } - - if (_log.isDebugEnabled()) { - _log.debug("Deleting data for " + portletId); - } - - PortletPreferencesImpl portletPreferencesImpl = - (PortletPreferencesImpl) - PortletPreferencesFactoryUtil.fromDefaultXML( - portletPreferences.getPreferences()); - - try { - portletPreferencesImpl = - (PortletPreferencesImpl)portletDataHandler.deleteData( - portletDataContext, portletId, portletPreferencesImpl); - } - finally { - portletDataContext.setGroupId(portletDataContext.getScopeGroupId()); - } - - if (portletPreferencesImpl == null) { - return null; - } - - return PortletPreferencesFactoryUtil.toXML(portletPreferencesImpl); - } - - protected void doImportPortletInfo( - long userId, long plid, long groupId, String portletId, - Map 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(), - 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); - - if ((userId > 0) && - ((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) || - (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6))) { - - Indexer indexer = IndexerRegistryUtil.getIndexer(User.class); - - indexer.reindex(userId); - } - } - - // 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(); - } - - /** - * @see {@link DLPortletDataHandlerImpl#getFileEntryTypeName(String, long, - * long, String, int)} - * @see {@link DLPortletDataHandlerImpl#getFolderName(String, long, long, - * String, int)} - */ - protected String getAssetCategoryName( - String uuid, long parentCategoryId, String name, int count) - throws Exception { - - AssetCategory assetCategory = null; - - try { - assetCategory = AssetCategoryUtil.findByP_N_First( - parentCategoryId, name, null); - } - catch (NoSuchCategoryException nsce) { - return name; - } - - if (Validator.isNotNull(uuid) && uuid.equals(assetCategory.getUuid())) { - return name; - } - - name = StringUtil.appendParentheticalSuffix(name, count); - - return getAssetCategoryName(uuid, parentCategoryId, name, ++count); - } - - protected String getAssetCategoryPath( - PortletDataContext portletDataContext, long assetCategoryId) { - - StringBundler sb = new StringBundler(6); - - sb.append(portletDataContext.getSourceRootPath()); - sb.append("/categories/"); - sb.append(assetCategoryId); - sb.append(".xml"); - - return sb.toString(); - } - - protected Map getAssetCategoryTitleMap( - AssetCategory assetCategory, String name) { - - Map titleMap = assetCategory.getTitleMap(); - - if (titleMap == null) { - titleMap = new HashMap(); - } - - Locale locale = LocaleUtil.getDefault(); - - titleMap.put(locale, name); - - return titleMap; - } - - /** - * @see {@link DLPortletDataHandlerImpl#getFileEntryTypeName(String, long, - * long, String, int)} - * @see {@link DLPortletDataHandlerImpl#getFolderName(String, long, long, - * String, int)} - */ - protected String getAssetVocabularyName( - String uuid, long groupId, String name, int count) - throws Exception { - - AssetVocabulary assetVocabulary = AssetVocabularyUtil.fetchByG_N( - groupId, name); - - if (assetVocabulary == null) { - return name; - } - - if (Validator.isNotNull(uuid) && - uuid.equals(assetVocabulary.getUuid())) { - - return name; - } - - name = StringUtil.appendParentheticalSuffix(name, count); - - return getAssetVocabularyName(uuid, groupId, name, ++count); - } - - protected Map getAssetVocabularyTitleMap( - AssetVocabulary assetVocabulary, String name) { - - Map titleMap = assetVocabulary.getTitleMap(); - - if (titleMap == null) { - titleMap = new HashMap(); - } - - Locale locale = LocaleUtil.getDefault(); - - titleMap.put(locale, name); - - return titleMap; - } - - protected UserIdStrategy getUserIdStrategy( - User user, String userIdStrategy) { - - if (UserIdStrategy.ALWAYS_CURRENT_USER_ID.equals(userIdStrategy)) { - return new AlwaysCurrentUserIdStrategy(user); - } - - return new CurrentUserIdStrategy(user); - } - - protected void importAssetCategory( - PortletDataContext portletDataContext, - Map assetVocabularyPKs, - Map assetCategoryPKs, - Map assetCategoryUuids, - Element assetCategoryElement, AssetCategory assetCategory) - throws Exception { - - long userId = portletDataContext.getUserId(assetCategory.getUserUuid()); - long assetVocabularyId = MapUtil.getLong( - assetVocabularyPKs, assetCategory.getVocabularyId(), - assetCategory.getVocabularyId()); - long parentAssetCategoryId = MapUtil.getLong( - assetCategoryPKs, assetCategory.getParentCategoryId(), - assetCategory.getParentCategoryId()); - - if ((parentAssetCategoryId != - AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) && - (parentAssetCategoryId == assetCategory.getParentCategoryId())) { - - String path = getAssetCategoryPath( - portletDataContext, parentAssetCategoryId); - - AssetCategory parentAssetCategory = - (AssetCategory)portletDataContext.getZipEntryAsObject(path); - - Node parentCategoryNode = - assetCategoryElement.getParent().selectSingleNode( - "./category[@path='" + path + "']"); - - if (parentCategoryNode != null) { - importAssetCategory( - portletDataContext, assetVocabularyPKs, assetCategoryPKs, - assetCategoryUuids, (Element)parentCategoryNode, - parentAssetCategory); - - parentAssetCategoryId = MapUtil.getLong( - assetCategoryPKs, assetCategory.getParentCategoryId(), - assetCategory.getParentCategoryId()); - } - } - - ServiceContext serviceContext = new ServiceContext(); - - serviceContext.setAddGroupPermissions(true); - serviceContext.setAddGuestPermissions(true); - serviceContext.setCreateDate(assetCategory.getCreateDate()); - serviceContext.setModifiedDate(assetCategory.getModifiedDate()); - serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId()); - - AssetCategory importedAssetCategory = null; - - try { - if (parentAssetCategoryId != - AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) { - - AssetCategoryUtil.findByPrimaryKey(parentAssetCategoryId); - } - - List propertyElements = assetCategoryElement.elements( - "property"); - - String[] properties = new String[propertyElements.size()]; - - for (int i = 0; i < propertyElements.size(); i++) { - Element propertyElement = propertyElements.get(i); - - String key = propertyElement.attributeValue("key"); - String value = propertyElement.attributeValue("value"); - - properties[i] = key.concat(StringPool.COLON).concat(value); - } - - AssetCategory existingAssetCategory = - AssetCategoryUtil.fetchByUUID_G( - assetCategory.getUuid(), - portletDataContext.getScopeGroupId()); - - if (existingAssetCategory == null) { - String name = getAssetCategoryName( - null, parentAssetCategoryId, assetCategory.getName(), 2); - - serviceContext.setUuid(assetCategory.getUuid()); - - importedAssetCategory = - AssetCategoryLocalServiceUtil.addCategory( - userId, parentAssetCategoryId, - getAssetCategoryTitleMap(assetCategory, name), - assetCategory.getDescriptionMap(), assetVocabularyId, - properties, serviceContext); - } - else { - String name = getAssetCategoryName( - assetCategory.getUuid(), parentAssetCategoryId, - assetCategory.getName(), 2); - - importedAssetCategory = - AssetCategoryLocalServiceUtil.updateCategory( - userId, existingAssetCategory.getCategoryId(), - parentAssetCategoryId, - getAssetCategoryTitleMap(assetCategory, name), - assetCategory.getDescriptionMap(), assetVocabularyId, - properties, serviceContext); - } - - assetCategoryPKs.put( - assetCategory.getCategoryId(), - importedAssetCategory.getCategoryId()); - - assetCategoryUuids.put( - assetCategory.getUuid(), importedAssetCategory.getUuid()); - - portletDataContext.importPermissions( - AssetCategory.class, assetCategory.getCategoryId(), - importedAssetCategory.getCategoryId()); - } - catch (NoSuchCategoryException nsce) { - _log.error( - "Could not find the parent category for category " + - assetCategory.getCategoryId()); - } - } - - protected void importAssetTag( - PortletDataContext portletDataContext, Map assetTagPKs, - Element assetTagElement, AssetTag assetTag) - throws SystemException, PortalException { - - long userId = portletDataContext.getUserId(assetTag.getUserUuid()); - - ServiceContext serviceContext = new ServiceContext(); - - serviceContext.setAddGroupPermissions(true); - serviceContext.setAddGuestPermissions(true); - serviceContext.setCreateDate(assetTag.getCreateDate()); - serviceContext.setModifiedDate(assetTag.getModifiedDate()); - serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId()); - - AssetTag importedAssetTag = null; - - List propertyElements = assetTagElement.elements("property"); - - String[] properties = new String[propertyElements.size()]; - - for (int i = 0; i < propertyElements.size(); i++) { - Element propertyElement = propertyElements.get(i); - - String key = propertyElement.attributeValue("key"); - String value = propertyElement.attributeValue("value"); - - properties[i] = key.concat(StringPool.COLON).concat(value); - } - - AssetTag existingAssetTag = null; - - try { - existingAssetTag = AssetTagUtil.findByG_N( - portletDataContext.getScopeGroupId(), assetTag.getName()); - } - catch (NoSuchTagException nste) { - if (_log.isDebugEnabled()) { - StringBundler sb = new StringBundler(5); - - sb.append("No AssetTag exists with the key {groupId="); - sb.append(portletDataContext.getScopeGroupId()); - sb.append(", name="); - sb.append(assetTag.getName()); - sb.append("}"); - - _log.debug(sb.toString()); - } - } - - try { - if (existingAssetTag == null) { - importedAssetTag = AssetTagLocalServiceUtil.addTag( - userId, assetTag.getName(), properties, serviceContext); - } - else { - importedAssetTag = AssetTagLocalServiceUtil.updateTag( - userId, existingAssetTag.getTagId(), assetTag.getName(), - properties, serviceContext); - } - - assetTagPKs.put(assetTag.getTagId(), importedAssetTag.getTagId()); - - portletDataContext.importPermissions( - AssetTag.class, assetTag.getTagId(), - importedAssetTag.getTagId()); - } - catch (NoSuchTagException nste) { - _log.error( - "Could not find the parent category for category " + - assetTag.getTagId()); - } - } - - protected void importAssetVocabulary( - PortletDataContext portletDataContext, - Map assetVocabularyPKs, Element assetVocabularyElement, - AssetVocabulary assetVocabulary) - throws Exception { - - long userId = portletDataContext.getUserId( - assetVocabulary.getUserUuid()); - long groupId = portletDataContext.getScopeGroupId(); - - ServiceContext serviceContext = new ServiceContext(); - - serviceContext.setAddGroupPermissions(true); - serviceContext.setAddGuestPermissions(true); - serviceContext.setCreateDate(assetVocabulary.getCreateDate()); - serviceContext.setModifiedDate(assetVocabulary.getModifiedDate()); - serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId()); - - AssetVocabulary importedAssetVocabulary = null; - - AssetVocabulary existingAssetVocabulary = - AssetVocabularyUtil.fetchByUUID_G( - assetVocabulary.getUuid(), groupId); - - if (existingAssetVocabulary == null) { - Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( - portletDataContext.getCompanyId()); - - existingAssetVocabulary = AssetVocabularyUtil.fetchByUUID_G( - assetVocabulary.getUuid(), companyGroup.getGroupId()); - } - - if (existingAssetVocabulary == null) { - String name = getAssetVocabularyName( - null, groupId, assetVocabulary.getName(), 2); - - serviceContext.setUuid(assetVocabulary.getUuid()); - - importedAssetVocabulary = - AssetVocabularyLocalServiceUtil.addVocabulary( - userId, StringPool.BLANK, - getAssetVocabularyTitleMap(assetVocabulary, name), - assetVocabulary.getDescriptionMap(), - assetVocabulary.getSettings(), serviceContext); - } - else { - String name = getAssetVocabularyName( - assetVocabulary.getUuid(), groupId, assetVocabulary.getName(), - 2); - - importedAssetVocabulary = - AssetVocabularyLocalServiceUtil.updateVocabulary( - existingAssetVocabulary.getVocabularyId(), StringPool.BLANK, - getAssetVocabularyTitleMap(assetVocabulary, name), - assetVocabulary.getDescriptionMap(), - assetVocabulary.getSettings(), serviceContext); - } - - assetVocabularyPKs.put( - assetVocabulary.getVocabularyId(), - importedAssetVocabulary.getVocabularyId()); - - portletDataContext.importPermissions( - AssetVocabulary.class, assetVocabulary.getVocabularyId(), - importedAssetVocabulary.getVocabularyId()); - } - - protected void importPortletData( - PortletDataContext portletDataContext, String portletId, long plid, - Element portletDataElement) - throws Exception { - - long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT; - int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT; - - PortletPreferences portletPreferences = - PortletPreferencesUtil.fetchByO_O_P_P( - ownerId, ownerType, plid, portletId); - - if (portletPreferences == null) { - portletPreferences = - new com.liferay.portal.model.impl.PortletPreferencesImpl(); - } - - String xml = importPortletData( - portletDataContext, portletId, portletPreferences, - portletDataElement); - - if (xml != null) { - PortletPreferencesLocalServiceUtil.updatePreferences( - ownerId, ownerType, plid, portletId, xml); - } - } - - protected String importPortletData( - PortletDataContext portletDataContext, String portletId, - PortletPreferences portletPreferences, Element portletDataElement) - throws Exception { - - Portlet portlet = PortletLocalServiceUtil.getPortletById( - portletDataContext.getCompanyId(), portletId); - - if (portlet == null) { - if (_log.isDebugEnabled()) { - _log.debug( - "Do not import portlet data for " + portletId + - " because the portlet does not exist"); - } - - return null; - } - - PortletDataHandler portletDataHandler = - portlet.getPortletDataHandlerInstance(); - - if (portletDataHandler == null) { - if (_log.isDebugEnabled()) { - _log.debug( - "Do not import portlet data for " + portletId + - " because the portlet does not have a " + - "PortletDataHandler"); - } - - return null; - } - - if (_log.isDebugEnabled()) { - _log.debug("Importing data for " + portletId); - } - - PortletPreferencesImpl portletPreferencesImpl = null; - - if (portletPreferences != null) { - portletPreferencesImpl = - (PortletPreferencesImpl) - PortletPreferencesFactoryUtil.fromDefaultXML( - portletPreferences.getPreferences()); - } - - String portletData = portletDataContext.getZipEntryAsString( - portletDataElement.attributeValue("path")); - - try { - portletPreferencesImpl = - (PortletPreferencesImpl)portletDataHandler.importData( - portletDataContext, portletId, portletPreferencesImpl, - portletData); - } - catch (Exception e) { - throw e; - } - - if (portletPreferencesImpl == null) { - return null; - } - - return PortletPreferencesFactoryUtil.toXML(portletPreferencesImpl); - } - - protected void importPortletPreferences( - PortletDataContext portletDataContext, long companyId, long groupId, - Layout layout, String portletId, Element parentElement, - boolean importPortletSetup, boolean importPortletArchivedSetups, - boolean importPortletUserPreferences, boolean preserveScopeLayoutId) - throws Exception { - - long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId); - long plid = 0; - String scopeType = StringPool.BLANK; - String scopeLayoutUuid = StringPool.BLANK; - - if (layout != null) { - plid = layout.getPlid(); - - if (preserveScopeLayoutId && (portletId != null)) { - javax.portlet.PortletPreferences jxPreferences = - PortletPreferencesFactoryUtil.getLayoutPortletSetup( - layout, portletId); - - scopeType = GetterUtil.getString( - jxPreferences.getValue("lfrScopeType", null)); - scopeLayoutUuid = GetterUtil.getString( - jxPreferences.getValue("lfrScopeLayoutUuid", null)); - - portletDataContext.setScopeType(scopeType); - portletDataContext.setScopeLayoutUuid(scopeLayoutUuid); - } - } - - List portletPreferencesElements = parentElement.elements( - "portlet-preferences"); - - for (Element portletPreferencesElement : portletPreferencesElements) { - String path = portletPreferencesElement.attributeValue("path"); - - if (portletDataContext.isPathNotProcessed(path)) { - String xml = null; - - Element element = null; - - try { - xml = portletDataContext.getZipEntryAsString(path); - - Document preferencesDocument = SAXReaderUtil.read(xml); - - element = preferencesDocument.getRootElement(); - } - catch (DocumentException de) { - throw new SystemException(de); - } - - long ownerId = GetterUtil.getLong( - element.attributeValue("owner-id")); - int ownerType = GetterUtil.getInteger( - element.attributeValue("owner-type")); - - if (ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) { - continue; - } - - if (((ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) || - (ownerType == PortletKeys.PREFS_OWNER_TYPE_LAYOUT)) && - !importPortletSetup) { - - continue; - } - - if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) && - !importPortletArchivedSetups) { - - continue; - } - - if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) && - (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT) && - !importPortletUserPreferences) { - - continue; - } - - if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) { - plid = PortletKeys.PREFS_PLID_SHARED; - ownerId = portletDataContext.getScopeGroupId(); - } - - boolean defaultUser = GetterUtil.getBoolean( - element.attributeValue("default-user")); - - if (portletId == null) { - portletId = element.attributeValue("portlet-id"); - } - - if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) { - portletId = PortletConstants.getRootPortletId(portletId); - - String userUuid = element.attributeValue( - "archive-user-uuid"); - String name = element.attributeValue("archive-name"); - - long userId = portletDataContext.getUserId(userUuid); - - PortletItem portletItem = - PortletItemLocalServiceUtil.updatePortletItem( - userId, groupId, name, portletId, - PortletPreferences.class.getName()); - - plid = 0; - ownerId = portletItem.getPortletItemId(); - } - else if (ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) { - String userUuid = element.attributeValue("user-uuid"); - - ownerId = portletDataContext.getUserId(userUuid); - } - - if (defaultUser) { - ownerId = defaultUserId; - } - - xml = checkPortletPreferences( - portletDataContext, companyId, ownerId, ownerType, plid, - portletId, xml); - - PortletPreferencesLocalServiceUtil.updatePreferences( - ownerId, ownerType, plid, portletId, xml); - } - } - - if (preserveScopeLayoutId && (layout != null)) { - javax.portlet.PortletPreferences jxPreferences = - PortletPreferencesFactoryUtil.getLayoutPortletSetup( - layout, portletId); - - try { - jxPreferences.setValue("lfrScopeType", scopeType); - jxPreferences.setValue("lfrScopeLayoutUuid", scopeLayoutUuid); - - jxPreferences.store(); - } - finally { - portletDataContext.setScopeType(scopeType); - portletDataContext.setScopeLayoutUuid(scopeLayoutUuid); - } - } - } - - protected void readAssetCategories(PortletDataContext portletDataContext) - throws Exception { - - String xml = portletDataContext.getZipEntryAsString( - portletDataContext.getSourceRootPath() + - "/categories-hierarchy.xml"); - - if (xml == null) { - return; - } - - Document document = SAXReaderUtil.read(xml); - - Element rootElement = document.getRootElement(); - - Element assetVocabulariesElement = rootElement.element("vocabularies"); - - List assetVocabularyElements = - assetVocabulariesElement.elements("vocabulary"); - - Map assetVocabularyPKs = - (Map)portletDataContext.getNewPrimaryKeysMap( - AssetVocabulary.class); - - for (Element assetVocabularyElement : assetVocabularyElements) { - String path = assetVocabularyElement.attributeValue("path"); - - if (!portletDataContext.isPathNotProcessed(path)) { - continue; - } - - AssetVocabulary assetVocabulary = - (AssetVocabulary)portletDataContext.getZipEntryAsObject(path); - - importAssetVocabulary( - portletDataContext, assetVocabularyPKs, assetVocabularyElement, - assetVocabulary); - } - - Element assetCategoriesElement = rootElement.element("categories"); - - List assetCategoryElements = assetCategoriesElement.elements( - "category"); - - Map assetCategoryPKs = - (Map)portletDataContext.getNewPrimaryKeysMap( - AssetCategory.class); - - Map assetCategoryUuids = - (Map)portletDataContext.getNewPrimaryKeysMap( - AssetCategory.class.getName() + "uuid"); - - for (Element assetCategoryElement : assetCategoryElements) { - String path = assetCategoryElement.attributeValue("path"); - - if (!portletDataContext.isPathNotProcessed(path)) { - continue; - } - - AssetCategory assetCategory = - (AssetCategory)portletDataContext.getZipEntryAsObject(path); - - importAssetCategory( - portletDataContext, assetVocabularyPKs, assetCategoryPKs, - assetCategoryUuids, assetCategoryElement, assetCategory); - } - - Element assetsElement = rootElement.element("assets"); - - List assetElements = assetsElement.elements("asset"); - - for (Element assetElement : assetElements) { - String className = GetterUtil.getString( - assetElement.attributeValue("class-name")); - long classPK = GetterUtil.getLong( - assetElement.attributeValue("class-pk")); - String[] assetCategoryUuidArray = StringUtil.split( - GetterUtil.getString( - assetElement.attributeValue("category-uuids"))); - - long[] assetCategoryIds = new long[0]; - - for (String assetCategoryUuid : assetCategoryUuidArray) { - assetCategoryUuid = MapUtil.getString( - assetCategoryUuids, assetCategoryUuid, - assetCategoryUuid); - - AssetCategory assetCategory = AssetCategoryUtil.fetchByUUID_G( - assetCategoryUuid, portletDataContext.getScopeGroupId()); - - if (assetCategory == null) { - Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( - portletDataContext.getCompanyId()); - - assetCategory = AssetCategoryUtil.fetchByUUID_G( - assetCategoryUuid, companyGroup.getGroupId()); - } - - if (assetCategory != null) { - assetCategoryIds = ArrayUtil.append( - assetCategoryIds, assetCategory.getCategoryId()); - } - } - - portletDataContext.addAssetCategories( - className, classPK, assetCategoryIds); - } - } - - protected void readAssetLinks(PortletDataContext portletDataContext) - throws Exception { - - String xml = portletDataContext.getZipEntryAsString( - portletDataContext.getSourceRootPath() + "/links.xml"); - - if (xml == null) { - return; - } - - Document document = SAXReaderUtil.read(xml); - - Element rootElement = document.getRootElement(); - - List assetLinkElements = rootElement.elements("asset-link"); - - for (Element assetLinkElement : assetLinkElements) { - String sourceUuid = GetterUtil.getString( - assetLinkElement.attributeValue("source-uuid")); - String[] assetEntryUuidArray = StringUtil.split( - GetterUtil.getString( - assetLinkElement.attributeValue("target-uuids"))); - int assetLinkType = GetterUtil.getInteger( - assetLinkElement.attributeValue("type")); - - List assetEntryIds = new ArrayList(); - - for (String assetEntryUuid : assetEntryUuidArray) { - try { - AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry( - portletDataContext.getScopeGroupId(), assetEntryUuid); - - assetEntryIds.add(assetEntry.getEntryId()); - } - catch (NoSuchEntryException nsee) { - } - } - - if (assetEntryIds.isEmpty()) { - continue; - } - - long[] assetEntryIdsArray = ArrayUtil.toArray( - assetEntryIds.toArray(new Long[assetEntryIds.size()])); - - try { - AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry( - portletDataContext.getScopeGroupId(), sourceUuid); - - AssetLinkLocalServiceUtil.updateLinks( - assetEntry.getUserId(), assetEntry.getEntryId(), - assetEntryIdsArray, assetLinkType); - } - catch (NoSuchEntryException nsee) { - } - } - } - - protected void readAssetTags(PortletDataContext portletDataContext) - throws Exception { - - String xml = portletDataContext.getZipEntryAsString( - portletDataContext.getSourceRootPath() + "/tags.xml"); - - if (xml == null) { - return; - } - - Document document = SAXReaderUtil.read(xml); - - Element rootElement = document.getRootElement(); - - List assetTagElements = rootElement.elements("tag"); - - for (Element assetTagElement : assetTagElements) { - String path = assetTagElement.attributeValue("path"); - - if (!portletDataContext.isPathNotProcessed(path)) { - continue; - } - - AssetTag assetTag = - (AssetTag)portletDataContext.getZipEntryAsObject(path); - - Map assetTagPKs = - (Map)portletDataContext.getNewPrimaryKeysMap( - AssetTag.class); - - importAssetTag( - portletDataContext, assetTagPKs, assetTagElement, assetTag); - } - - List assetElements = rootElement.elements("asset"); - - for (Element assetElement : assetElements) { - String className = GetterUtil.getString( - assetElement.attributeValue("class-name")); - long classPK = GetterUtil.getLong( - assetElement.attributeValue("class-pk")); - String assetTagNames = GetterUtil.getString( - assetElement.attributeValue("tags")); - - portletDataContext.addAssetTags( - className, classPK, StringUtil.split(assetTagNames)); - } - } - - protected void readComments(PortletDataContext portletDataContext) - throws Exception { - - String xml = portletDataContext.getZipEntryAsString( - portletDataContext.getSourceRootPath() + "/comments.xml"); - - if (xml == null) { - return; - } - - Document document = SAXReaderUtil.read(xml); - - Element rootElement = document.getRootElement(); - - List assetElements = rootElement.elements("asset"); - - for (Element assetElement : assetElements) { - String path = assetElement.attributeValue("path"); - String className = assetElement.attributeValue("class-name"); - long classPK = GetterUtil.getLong( - assetElement.attributeValue("class-pk")); - - List zipFolderEntries = - portletDataContext.getZipFolderEntries(path); - - List mbMessages = new ArrayList(); - - for (String zipFolderEntry : zipFolderEntries) { - MBMessage mbMessage = - (MBMessage)portletDataContext.getZipEntryAsObject( - zipFolderEntry); - - if (mbMessage != null) { - mbMessages.add(mbMessage); - } - } - - portletDataContext.addComments(className, classPK, mbMessages); - } - } - - protected void readExpandoTables(PortletDataContext portletDataContext) - throws Exception { - - String xml = portletDataContext.getZipEntryAsString( - portletDataContext.getSourceRootPath() + "/expando-tables.xml"); - - if (xml == null) { - return; - } - - Document document = SAXReaderUtil.read(xml); - - Element rootElement = document.getRootElement(); - - List expandoTableElements = rootElement.elements( - "expando-table"); - - for (Element expandoTableElement : expandoTableElements) { - String className = expandoTableElement.attributeValue("class-name"); - - ExpandoTable expandoTable = null; - - try { - expandoTable = ExpandoTableLocalServiceUtil.getDefaultTable( - portletDataContext.getCompanyId(), className); - } - catch (NoSuchTableException nste) { - expandoTable = ExpandoTableLocalServiceUtil.addDefaultTable( - portletDataContext.getCompanyId(), className); - } - - List expandoColumnElements = expandoTableElement.elements( - "expando-column"); - - for (Element expandoColumnElement : expandoColumnElements) { - long columnId = GetterUtil.getLong( - expandoColumnElement.attributeValue("column-id")); - String name = expandoColumnElement.attributeValue("name"); - int type = GetterUtil.getInteger( - expandoColumnElement.attributeValue("type")); - String defaultData = expandoColumnElement.elementText( - "default-data"); - String typeSettings = expandoColumnElement.elementText( - "type-settings"); - - Serializable defaultDataObject = - ExpandoConverterUtil.getAttributeFromString( - type, defaultData); - - ExpandoColumn expandoColumn = - ExpandoColumnLocalServiceUtil.getColumn( - expandoTable.getTableId(), name); - - if (expandoColumn != null) { - ExpandoColumnLocalServiceUtil.updateColumn( - expandoColumn.getColumnId(), name, type, - defaultDataObject); - } - else { - expandoColumn = ExpandoColumnLocalServiceUtil.addColumn( - expandoTable.getTableId(), name, type, - defaultDataObject); - } - - ExpandoColumnLocalServiceUtil.updateTypeSettings( - expandoColumn.getColumnId(), typeSettings); - - portletDataContext.importPermissions( - ExpandoColumn.class, columnId, expandoColumn.getColumnId()); - } - } - } - - protected void readLocks(PortletDataContext portletDataContext) - throws Exception { - - String xml = portletDataContext.getZipEntryAsString( - portletDataContext.getSourceRootPath() + "/locks.xml"); - - if (xml == null) { - return; - } - - Document document = SAXReaderUtil.read(xml); - - Element rootElement = document.getRootElement(); - - List assetElements = rootElement.elements("asset"); - - for (Element assetElement : assetElements) { - String path = assetElement.attributeValue("path"); - String className = assetElement.attributeValue("class-name"); - String key = assetElement.attributeValue("key"); - - Lock lock = (Lock)portletDataContext.getZipEntryAsObject(path); - - if (lock != null) { - portletDataContext.addLocks(className, key, lock); - } - } - } - - protected void readRatingsEntries(PortletDataContext portletDataContext) - throws Exception { - - String xml = portletDataContext.getZipEntryAsString( - portletDataContext.getSourceRootPath() + "/ratings.xml"); - - if (xml == null) { - return; - } - - Document document = SAXReaderUtil.read(xml); - - Element rootElement = document.getRootElement(); - - List assetElements = rootElement.elements("asset"); - - for (Element assetElement : assetElements) { - String path = assetElement.attributeValue("path"); - String className = assetElement.attributeValue("class-name"); - long classPK = GetterUtil.getLong( - assetElement.attributeValue("class-pk")); - - List zipFolderEntries = - portletDataContext.getZipFolderEntries(path); - - List ratingsEntries = new ArrayList(); - - for (String zipFolderEntry : zipFolderEntries) { - RatingsEntry ratingsEntry = - (RatingsEntry)portletDataContext.getZipEntryAsObject( - zipFolderEntry); - - if (ratingsEntry != null) { - ratingsEntries.add(ratingsEntry); - } - } - - portletDataContext.addRatingsEntries( - className, classPK, ratingsEntries); - } - } - - protected void resetPortletScope( - PortletDataContext portletDataContext, long groupId) { - - portletDataContext.setScopeGroupId(groupId); - portletDataContext.setScopeLayoutUuid(StringPool.BLANK); - portletDataContext.setScopeType(StringPool.BLANK); - } - - protected void setPortletScope( - PortletDataContext portletDataContext, Element portletElement) { - - // Portlet data scope - - String scopeLayoutUuid = GetterUtil.getString( - portletElement.attributeValue("scope-layout-uuid")); - String scopeLayoutType = GetterUtil.getString( - portletElement.attributeValue("scope-layout-type")); - - portletDataContext.setScopeLayoutUuid(scopeLayoutUuid); - portletDataContext.setScopeType(scopeLayoutType); - - // Layout scope - - try { - Group scopeGroup = null; - - if (scopeLayoutType.equals("company")) { - scopeGroup = GroupLocalServiceUtil.getCompanyGroup( - portletDataContext.getCompanyId()); - } - else if (Validator.isNotNull(scopeLayoutUuid)) { - Layout scopeLayout = - LayoutLocalServiceUtil.getLayoutByUuidAndGroupId( - scopeLayoutUuid, portletDataContext.getGroupId()); - - if (scopeLayout.hasScopeGroup()) { - scopeGroup = scopeLayout.getScopeGroup(); - } - else { - String name = String.valueOf(scopeLayout.getPlid()); - - scopeGroup = GroupLocalServiceUtil.addGroup( - portletDataContext.getUserId(null), - Layout.class.getName(), scopeLayout.getPlid(), name, - null, 0, null, false, true, null); - } - - Group group = scopeLayout.getGroup(); - - if (group.isStaged() && !group.isStagedRemotely()) { - try { - Layout oldLayout = - LayoutLocalServiceUtil.getLayoutByUuidAndGroupId( - scopeLayoutUuid, - portletDataContext.getSourceGroupId()); - - Group oldScopeGroup = oldLayout.getScopeGroup(); - - oldScopeGroup.setLiveGroupId(scopeGroup.getGroupId()); - - GroupLocalServiceUtil.updateGroup(oldScopeGroup, true); - } - catch (NoSuchLayoutException nsle) { - if (_log.isWarnEnabled()) { - _log.warn(nsle); - } - } - } - - portletDataContext.setScopeGroupId(scopeGroup.getGroupId()); - } - } - catch (PortalException pe) { - } - catch (Exception e) { - _log.error(e, e); - } - } - - private static Log _log = LogFactoryUtil.getLog(PortletImporter.class); - - private PermissionImporter _permissionImporter = new PermissionImporter(); - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portal.lar; + +import com.liferay.portal.LARFileException; +import com.liferay.portal.LARTypeException; +import com.liferay.portal.LayoutImportException; +import com.liferay.portal.NoSuchLayoutException; +import com.liferay.portal.PortletIdException; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.lar.ImportExportThreadLocal; +import com.liferay.portal.kernel.lar.PortletDataContext; +import com.liferay.portal.kernel.lar.PortletDataHandler; +import com.liferay.portal.kernel.lar.PortletDataHandlerKeys; +import com.liferay.portal.kernel.lar.UserIdStrategy; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.search.Indexer; +import com.liferay.portal.kernel.search.IndexerRegistryUtil; +import com.liferay.portal.kernel.util.ArrayUtil; +import com.liferay.portal.kernel.util.GetterUtil; +import com.liferay.portal.kernel.util.LocaleUtil; +import com.liferay.portal.kernel.util.MapUtil; +import com.liferay.portal.kernel.util.ReleaseInfo; +import com.liferay.portal.kernel.util.StringBundler; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.kernel.xml.Document; +import com.liferay.portal.kernel.xml.DocumentException; +import com.liferay.portal.kernel.xml.Element; +import com.liferay.portal.kernel.xml.Node; +import com.liferay.portal.kernel.xml.SAXReaderUtil; +import com.liferay.portal.kernel.zip.ZipReader; +import com.liferay.portal.kernel.zip.ZipReaderFactoryUtil; +import com.liferay.portal.model.Group; +import com.liferay.portal.model.Layout; +import com.liferay.portal.model.Lock; +import com.liferay.portal.model.Portlet; +import com.liferay.portal.model.PortletConstants; +import com.liferay.portal.model.PortletItem; +import com.liferay.portal.model.PortletPreferences; +import com.liferay.portal.model.User; +import com.liferay.portal.security.permission.PermissionCacheUtil; +import com.liferay.portal.service.GroupLocalServiceUtil; +import com.liferay.portal.service.LayoutLocalServiceUtil; +import com.liferay.portal.service.PortletItemLocalServiceUtil; +import com.liferay.portal.service.PortletLocalServiceUtil; +import com.liferay.portal.service.PortletPreferencesLocalServiceUtil; +import com.liferay.portal.service.ServiceContext; +import com.liferay.portal.service.UserLocalServiceUtil; +import com.liferay.portal.service.persistence.PortletPreferencesUtil; +import com.liferay.portal.service.persistence.UserUtil; +import com.liferay.portal.servlet.filters.cache.CacheUtil; +import com.liferay.portal.util.PortletKeys; +import com.liferay.portal.util.PropsValues; +import com.liferay.portlet.PortletPreferencesFactoryUtil; +import com.liferay.portlet.PortletPreferencesImpl; +import com.liferay.portlet.asset.NoSuchCategoryException; +import com.liferay.portlet.asset.NoSuchEntryException; +import com.liferay.portlet.asset.NoSuchTagException; +import com.liferay.portlet.asset.model.AssetCategory; +import com.liferay.portlet.asset.model.AssetCategoryConstants; +import com.liferay.portlet.asset.model.AssetEntry; +import com.liferay.portlet.asset.model.AssetTag; +import com.liferay.portlet.asset.model.AssetVocabulary; +import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil; +import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil; +import com.liferay.portlet.asset.service.AssetLinkLocalServiceUtil; +import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil; +import com.liferay.portlet.asset.service.AssetVocabularyLocalServiceUtil; +import com.liferay.portlet.asset.service.persistence.AssetCategoryUtil; +import com.liferay.portlet.asset.service.persistence.AssetTagUtil; +import com.liferay.portlet.asset.service.persistence.AssetVocabularyUtil; +import com.liferay.portlet.expando.NoSuchTableException; +import com.liferay.portlet.expando.model.ExpandoColumn; +import com.liferay.portlet.expando.model.ExpandoTable; +import com.liferay.portlet.expando.service.ExpandoColumnLocalServiceUtil; +import com.liferay.portlet.expando.service.ExpandoTableLocalServiceUtil; +import com.liferay.portlet.expando.util.ExpandoConverterUtil; +import com.liferay.portlet.journalcontent.util.JournalContentUtil; +import com.liferay.portlet.messageboards.model.MBMessage; +import com.liferay.portlet.ratings.model.RatingsEntry; + +import java.io.File; +import java.io.Serializable; + +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import org.apache.commons.lang.time.StopWatch; + +/** + * @author Brian Wing Shun Chan + * @author Joel Kozikowski + * @author Charles May + * @author Raymond Augé + * @author Jorge Ferrer + * @author Bruno Farache + * @author Zsigmond Rab + * @author Douglas Wong + */ +public class PortletImporter { + + public void importPortletInfo( + long userId, long plid, long groupId, String portletId, + Map parameterMap, File file) + throws Exception { + + try { + ImportExportThreadLocal.setPortletImportInProcess(true); + + doImportPortletInfo( + userId, plid, groupId, portletId, parameterMap, file); + } + finally { + ImportExportThreadLocal.setPortletImportInProcess(false); + + CacheUtil.clearCache(); + JournalContentUtil.clearCache(); + PermissionCacheUtil.clearCache(); + } + } + + protected String checkPortletPreferences( + PortletDataContext portletDataContext, long companyId, long ownerId, + int ownerType, long plid, String portletId, String xml) + throws Exception { + + String rootPotletId = PortletConstants.getRootPortletId(portletId); + + if (!rootPotletId.equals(PortletKeys.ASSET_PUBLISHER)) { + return xml; + } + + PortletPreferencesImpl portletPreferences = + (PortletPreferencesImpl)PortletPreferencesFactoryUtil. + fromXML(companyId, ownerId, ownerType, plid, portletId, xml); + + Enumeration enu = portletPreferences.getNames(); + + while (enu.hasMoreElements()) { + String name = enu.nextElement(); + + String value = GetterUtil.getString( + portletPreferences.getValue(name, StringPool.BLANK)); + + String prefix = "queryName"; + + if (value.equalsIgnoreCase("assetCategories") && + name.startsWith(prefix)) { + + String index = name.substring(prefix.length(), name.length()); + + String queryValuesName = "queryValues" + index; + + String[] importedAssetCategoryPKs = + portletPreferences.getValues(queryValuesName, null); + + Map assetCategoryPKs = + (Map)portletDataContext.getNewPrimaryKeysMap( + AssetCategory.class); + + String[] newAssetCategoryPKs = new String[ + importedAssetCategoryPKs.length]; + + int i = 0; + + for (String importedAssetCategoryPK : + importedAssetCategoryPKs) { + + String newAssetCategoryPK = StringUtil.valueOf( + assetCategoryPKs.get( + new Long(importedAssetCategoryPK))); + + if (Validator.isNull(newAssetCategoryPK)) { + newAssetCategoryPK = importedAssetCategoryPK; + } + + newAssetCategoryPKs[i++] = newAssetCategoryPK; + } + + portletPreferences.setValues( + queryValuesName, newAssetCategoryPKs); + } + } + + return PortletPreferencesFactoryUtil.toXML(portletPreferences); + } + + protected void deletePortletData( + PortletDataContext portletDataContext, String portletId, long plid) + throws Exception { + + long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT; + int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT; + + PortletPreferences portletPreferences = + PortletPreferencesUtil.fetchByO_O_P_P( + ownerId, ownerType, plid, portletId); + + if (portletPreferences == null) { + portletPreferences = + new com.liferay.portal.model.impl.PortletPreferencesImpl(); + } + + String xml = deletePortletData( + portletDataContext, portletId, portletPreferences); + + if (xml != null) { + PortletPreferencesLocalServiceUtil.updatePreferences( + ownerId, ownerType, plid, portletId, xml); + } + } + + protected String deletePortletData( + PortletDataContext portletDataContext, String portletId, + PortletPreferences portletPreferences) + throws Exception { + + Portlet portlet = PortletLocalServiceUtil.getPortletById( + portletDataContext.getCompanyId(), portletId); + + if (portlet == null) { + if (_log.isDebugEnabled()) { + _log.debug( + "Do not delete portlet data for " + portletId + + " because the portlet does not exist"); + } + + return null; + } + + PortletDataHandler portletDataHandler = + portlet.getPortletDataHandlerInstance(); + + if (portletDataHandler == null) { + if (_log.isDebugEnabled()) { + _log.debug( + "Do not delete portlet data for " + portletId + + " because the portlet does not have a " + + "PortletDataHandler"); + } + + return null; + } + + if (_log.isDebugEnabled()) { + _log.debug("Deleting data for " + portletId); + } + + PortletPreferencesImpl portletPreferencesImpl = + (PortletPreferencesImpl) + PortletPreferencesFactoryUtil.fromDefaultXML( + portletPreferences.getPreferences()); + + try { + portletPreferencesImpl = + (PortletPreferencesImpl)portletDataHandler.deleteData( + portletDataContext, portletId, portletPreferencesImpl); + } + finally { + portletDataContext.setGroupId(portletDataContext.getScopeGroupId()); + } + + if (portletPreferencesImpl == null) { + return null; + } + + return PortletPreferencesFactoryUtil.toXML(portletPreferencesImpl); + } + + protected void doImportPortletInfo( + long userId, long plid, long groupId, String portletId, + Map 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(), + 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); + + if ((userId > 0) && + ((PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) || + (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6))) { + + Indexer indexer = IndexerRegistryUtil.getIndexer(User.class); + + indexer.reindex(userId); + } + } + + // 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(); + } + + /** + * @see {@link DLPortletDataHandlerImpl#getFileEntryTypeName(String, long, + * long, String, int)} + * @see {@link DLPortletDataHandlerImpl#getFolderName(String, long, long, + * String, int)} + */ + protected String getAssetCategoryName( + String uuid, long parentCategoryId, String name, int count) + throws Exception { + + AssetCategory assetCategory = null; + + try { + assetCategory = AssetCategoryUtil.findByP_N_First( + parentCategoryId, name, null); + } + catch (NoSuchCategoryException nsce) { + return name; + } + + if (Validator.isNotNull(uuid) && uuid.equals(assetCategory.getUuid())) { + return name; + } + + name = StringUtil.appendParentheticalSuffix(name, count); + + return getAssetCategoryName(uuid, parentCategoryId, name, ++count); + } + + protected String getAssetCategoryPath( + PortletDataContext portletDataContext, long assetCategoryId) { + + StringBundler sb = new StringBundler(6); + + sb.append(portletDataContext.getSourceRootPath()); + sb.append("/categories/"); + sb.append(assetCategoryId); + sb.append(".xml"); + + return sb.toString(); + } + + protected Map getAssetCategoryTitleMap( + AssetCategory assetCategory, String name) { + + Map titleMap = assetCategory.getTitleMap(); + + if (titleMap == null) { + titleMap = new HashMap(); + } + + Locale locale = LocaleUtil.getDefault(); + + titleMap.put(locale, name); + + return titleMap; + } + + /** + * @see {@link DLPortletDataHandlerImpl#getFileEntryTypeName(String, long, + * long, String, int)} + * @see {@link DLPortletDataHandlerImpl#getFolderName(String, long, long, + * String, int)} + */ + protected String getAssetVocabularyName( + String uuid, long groupId, String name, int count) + throws Exception { + + AssetVocabulary assetVocabulary = AssetVocabularyUtil.fetchByG_N( + groupId, name); + + if (assetVocabulary == null) { + return name; + } + + if (Validator.isNotNull(uuid) && + uuid.equals(assetVocabulary.getUuid())) { + + return name; + } + + name = StringUtil.appendParentheticalSuffix(name, count); + + return getAssetVocabularyName(uuid, groupId, name, ++count); + } + + protected Map getAssetVocabularyTitleMap( + AssetVocabulary assetVocabulary, String name) { + + Map titleMap = assetVocabulary.getTitleMap(); + + if (titleMap == null) { + titleMap = new HashMap(); + } + + Locale locale = LocaleUtil.getDefault(); + + titleMap.put(locale, name); + + return titleMap; + } + + protected UserIdStrategy getUserIdStrategy( + User user, String userIdStrategy) { + + if (UserIdStrategy.ALWAYS_CURRENT_USER_ID.equals(userIdStrategy)) { + return new AlwaysCurrentUserIdStrategy(user); + } + + return new CurrentUserIdStrategy(user); + } + + protected void importAssetCategory( + PortletDataContext portletDataContext, + Map assetVocabularyPKs, + Map assetCategoryPKs, + Map assetCategoryUuids, + Element assetCategoryElement, AssetCategory assetCategory) + throws Exception { + + long userId = portletDataContext.getUserId(assetCategory.getUserUuid()); + long assetVocabularyId = MapUtil.getLong( + assetVocabularyPKs, assetCategory.getVocabularyId(), + assetCategory.getVocabularyId()); + long parentAssetCategoryId = MapUtil.getLong( + assetCategoryPKs, assetCategory.getParentCategoryId(), + assetCategory.getParentCategoryId()); + + if ((parentAssetCategoryId != + AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) && + (parentAssetCategoryId == assetCategory.getParentCategoryId())) { + + String path = getAssetCategoryPath( + portletDataContext, parentAssetCategoryId); + + AssetCategory parentAssetCategory = + (AssetCategory)portletDataContext.getZipEntryAsObject(path); + + Node parentCategoryNode = + assetCategoryElement.getParent().selectSingleNode( + "./category[@path='" + path + "']"); + + if (parentCategoryNode != null) { + importAssetCategory( + portletDataContext, assetVocabularyPKs, assetCategoryPKs, + assetCategoryUuids, (Element)parentCategoryNode, + parentAssetCategory); + + parentAssetCategoryId = MapUtil.getLong( + assetCategoryPKs, assetCategory.getParentCategoryId(), + assetCategory.getParentCategoryId()); + } + } + + ServiceContext serviceContext = new ServiceContext(); + + serviceContext.setAddGroupPermissions(true); + serviceContext.setAddGuestPermissions(true); + serviceContext.setCreateDate(assetCategory.getCreateDate()); + serviceContext.setModifiedDate(assetCategory.getModifiedDate()); + serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId()); + + AssetCategory importedAssetCategory = null; + + try { + if (parentAssetCategoryId != + AssetCategoryConstants.DEFAULT_PARENT_CATEGORY_ID) { + + AssetCategoryUtil.findByPrimaryKey(parentAssetCategoryId); + } + + List propertyElements = assetCategoryElement.elements( + "property"); + + String[] properties = new String[propertyElements.size()]; + + for (int i = 0; i < propertyElements.size(); i++) { + Element propertyElement = propertyElements.get(i); + + String key = propertyElement.attributeValue("key"); + String value = propertyElement.attributeValue("value"); + + properties[i] = key.concat(StringPool.COLON).concat(value); + } + + AssetCategory existingAssetCategory = + AssetCategoryUtil.fetchByUUID_G( + assetCategory.getUuid(), + portletDataContext.getScopeGroupId()); + + if (existingAssetCategory == null) { + String name = getAssetCategoryName( + null, parentAssetCategoryId, assetCategory.getName(), 2); + + serviceContext.setUuid(assetCategory.getUuid()); + + importedAssetCategory = + AssetCategoryLocalServiceUtil.addCategory( + userId, parentAssetCategoryId, + getAssetCategoryTitleMap(assetCategory, name), + assetCategory.getDescriptionMap(), assetVocabularyId, + properties, serviceContext); + } + else { + String name = getAssetCategoryName( + assetCategory.getUuid(), parentAssetCategoryId, + assetCategory.getName(), 2); + + importedAssetCategory = + AssetCategoryLocalServiceUtil.updateCategory( + userId, existingAssetCategory.getCategoryId(), + parentAssetCategoryId, + getAssetCategoryTitleMap(assetCategory, name), + assetCategory.getDescriptionMap(), assetVocabularyId, + properties, serviceContext); + } + + assetCategoryPKs.put( + assetCategory.getCategoryId(), + importedAssetCategory.getCategoryId()); + + assetCategoryUuids.put( + assetCategory.getUuid(), importedAssetCategory.getUuid()); + + portletDataContext.importPermissions( + AssetCategory.class, assetCategory.getCategoryId(), + importedAssetCategory.getCategoryId()); + } + catch (NoSuchCategoryException nsce) { + _log.error( + "Could not find the parent category for category " + + assetCategory.getCategoryId()); + } + } + + protected void importAssetTag( + PortletDataContext portletDataContext, Map assetTagPKs, + Element assetTagElement, AssetTag assetTag) + throws SystemException, PortalException { + + long userId = portletDataContext.getUserId(assetTag.getUserUuid()); + + ServiceContext serviceContext = new ServiceContext(); + + serviceContext.setAddGroupPermissions(true); + serviceContext.setAddGuestPermissions(true); + serviceContext.setCreateDate(assetTag.getCreateDate()); + serviceContext.setModifiedDate(assetTag.getModifiedDate()); + serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId()); + + AssetTag importedAssetTag = null; + + List propertyElements = assetTagElement.elements("property"); + + String[] properties = new String[propertyElements.size()]; + + for (int i = 0; i < propertyElements.size(); i++) { + Element propertyElement = propertyElements.get(i); + + String key = propertyElement.attributeValue("key"); + String value = propertyElement.attributeValue("value"); + + properties[i] = key.concat(StringPool.COLON).concat(value); + } + + AssetTag existingAssetTag = null; + + try { + existingAssetTag = AssetTagUtil.findByG_N( + portletDataContext.getScopeGroupId(), assetTag.getName()); + } + catch (NoSuchTagException nste) { + if (_log.isDebugEnabled()) { + StringBundler sb = new StringBundler(5); + + sb.append("No AssetTag exists with the key {groupId="); + sb.append(portletDataContext.getScopeGroupId()); + sb.append(", name="); + sb.append(assetTag.getName()); + sb.append("}"); + + _log.debug(sb.toString()); + } + } + + try { + if (existingAssetTag == null) { + importedAssetTag = AssetTagLocalServiceUtil.addTag( + userId, assetTag.getName(), properties, serviceContext); + } + else { + importedAssetTag = AssetTagLocalServiceUtil.updateTag( + userId, existingAssetTag.getTagId(), assetTag.getName(), + properties, serviceContext); + } + + assetTagPKs.put(assetTag.getTagId(), importedAssetTag.getTagId()); + + portletDataContext.importPermissions( + AssetTag.class, assetTag.getTagId(), + importedAssetTag.getTagId()); + } + catch (NoSuchTagException nste) { + _log.error( + "Could not find the parent category for category " + + assetTag.getTagId()); + } + } + + protected void importAssetVocabulary( + PortletDataContext portletDataContext, + Map assetVocabularyPKs, Element assetVocabularyElement, + AssetVocabulary assetVocabulary) + throws Exception { + + long userId = portletDataContext.getUserId( + assetVocabulary.getUserUuid()); + long groupId = portletDataContext.getScopeGroupId(); + + ServiceContext serviceContext = new ServiceContext(); + + serviceContext.setAddGroupPermissions(true); + serviceContext.setAddGuestPermissions(true); + serviceContext.setCreateDate(assetVocabulary.getCreateDate()); + serviceContext.setModifiedDate(assetVocabulary.getModifiedDate()); + serviceContext.setScopeGroupId(portletDataContext.getScopeGroupId()); + + AssetVocabulary importedAssetVocabulary = null; + + AssetVocabulary existingAssetVocabulary = + AssetVocabularyUtil.fetchByUUID_G( + assetVocabulary.getUuid(), groupId); + + if (existingAssetVocabulary == null) { + Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( + portletDataContext.getCompanyId()); + + existingAssetVocabulary = AssetVocabularyUtil.fetchByUUID_G( + assetVocabulary.getUuid(), companyGroup.getGroupId()); + } + + if (existingAssetVocabulary == null) { + String name = getAssetVocabularyName( + null, groupId, assetVocabulary.getName(), 2); + + serviceContext.setUuid(assetVocabulary.getUuid()); + + importedAssetVocabulary = + AssetVocabularyLocalServiceUtil.addVocabulary( + userId, StringPool.BLANK, + getAssetVocabularyTitleMap(assetVocabulary, name), + assetVocabulary.getDescriptionMap(), + assetVocabulary.getSettings(), serviceContext); + } + else { + String name = getAssetVocabularyName( + assetVocabulary.getUuid(), groupId, assetVocabulary.getName(), + 2); + + importedAssetVocabulary = + AssetVocabularyLocalServiceUtil.updateVocabulary( + existingAssetVocabulary.getVocabularyId(), StringPool.BLANK, + getAssetVocabularyTitleMap(assetVocabulary, name), + assetVocabulary.getDescriptionMap(), + assetVocabulary.getSettings(), serviceContext); + } + + assetVocabularyPKs.put( + assetVocabulary.getVocabularyId(), + importedAssetVocabulary.getVocabularyId()); + + portletDataContext.importPermissions( + AssetVocabulary.class, assetVocabulary.getVocabularyId(), + importedAssetVocabulary.getVocabularyId()); + } + + protected void importPortletData( + PortletDataContext portletDataContext, String portletId, long plid, + Element portletDataElement) + throws Exception { + + long ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT; + int ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT; + + PortletPreferences portletPreferences = + PortletPreferencesUtil.fetchByO_O_P_P( + ownerId, ownerType, plid, portletId); + + if (portletPreferences == null) { + portletPreferences = + new com.liferay.portal.model.impl.PortletPreferencesImpl(); + } + + String xml = importPortletData( + portletDataContext, portletId, portletPreferences, + portletDataElement); + + if (xml != null) { + PortletPreferencesLocalServiceUtil.updatePreferences( + ownerId, ownerType, plid, portletId, xml); + } + } + + protected String importPortletData( + PortletDataContext portletDataContext, String portletId, + PortletPreferences portletPreferences, Element portletDataElement) + throws Exception { + + Portlet portlet = PortletLocalServiceUtil.getPortletById( + portletDataContext.getCompanyId(), portletId); + + if (portlet == null) { + if (_log.isDebugEnabled()) { + _log.debug( + "Do not import portlet data for " + portletId + + " because the portlet does not exist"); + } + + return null; + } + + PortletDataHandler portletDataHandler = + portlet.getPortletDataHandlerInstance(); + + if (portletDataHandler == null) { + if (_log.isDebugEnabled()) { + _log.debug( + "Do not import portlet data for " + portletId + + " because the portlet does not have a " + + "PortletDataHandler"); + } + + return null; + } + + if (_log.isDebugEnabled()) { + _log.debug("Importing data for " + portletId); + } + + PortletPreferencesImpl portletPreferencesImpl = null; + + if (portletPreferences != null) { + portletPreferencesImpl = + (PortletPreferencesImpl) + PortletPreferencesFactoryUtil.fromDefaultXML( + portletPreferences.getPreferences()); + } + + String portletData = portletDataContext.getZipEntryAsString( + portletDataElement.attributeValue("path")); + + try { + portletPreferencesImpl = + (PortletPreferencesImpl)portletDataHandler.importData( + portletDataContext, portletId, portletPreferencesImpl, + portletData); + } + catch (Exception e) { + throw e; + } + + if (portletPreferencesImpl == null) { + return null; + } + + return PortletPreferencesFactoryUtil.toXML(portletPreferencesImpl); + } + + protected void importPortletPreferences( + PortletDataContext portletDataContext, long companyId, long groupId, + Layout layout, String portletId, Element parentElement, + boolean importPortletSetup, boolean importPortletArchivedSetups, + boolean importPortletUserPreferences, boolean preserveScopeLayoutId) + throws Exception { + + long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId); + long plid = 0; + String scopeType = StringPool.BLANK; + String scopeLayoutUuid = StringPool.BLANK; + + if (layout != null) { + plid = layout.getPlid(); + + if (preserveScopeLayoutId && (portletId != null)) { + javax.portlet.PortletPreferences jxPreferences = + PortletPreferencesFactoryUtil.getLayoutPortletSetup( + layout, portletId); + + scopeType = GetterUtil.getString( + jxPreferences.getValue("lfrScopeType", null)); + scopeLayoutUuid = GetterUtil.getString( + jxPreferences.getValue("lfrScopeLayoutUuid", null)); + + portletDataContext.setScopeType(scopeType); + portletDataContext.setScopeLayoutUuid(scopeLayoutUuid); + } + } + + List portletPreferencesElements = parentElement.elements( + "portlet-preferences"); + + for (Element portletPreferencesElement : portletPreferencesElements) { + String path = portletPreferencesElement.attributeValue("path"); + + if (portletDataContext.isPathNotProcessed(path)) { + String xml = null; + + Element element = null; + + try { + xml = portletDataContext.getZipEntryAsString(path); + + Document preferencesDocument = SAXReaderUtil.read(xml); + + element = preferencesDocument.getRootElement(); + } + catch (DocumentException de) { + throw new SystemException(de); + } + + long ownerId = GetterUtil.getLong( + element.attributeValue("owner-id")); + int ownerType = GetterUtil.getInteger( + element.attributeValue("owner-type")); + + if (ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) { + continue; + } + + if (((ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) || + (ownerType == PortletKeys.PREFS_OWNER_TYPE_LAYOUT)) && + !importPortletSetup) { + + continue; + } + + if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) && + !importPortletArchivedSetups) { + + continue; + } + + if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) && + (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT) && + !importPortletUserPreferences) { + + continue; + } + + if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) { + plid = PortletKeys.PREFS_PLID_SHARED; + ownerId = portletDataContext.getScopeGroupId(); + } + + boolean defaultUser = GetterUtil.getBoolean( + element.attributeValue("default-user")); + + if (portletId == null) { + portletId = element.attributeValue("portlet-id"); + } + + if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) { + portletId = PortletConstants.getRootPortletId(portletId); + + String userUuid = element.attributeValue( + "archive-user-uuid"); + String name = element.attributeValue("archive-name"); + + long userId = portletDataContext.getUserId(userUuid); + + PortletItem portletItem = + PortletItemLocalServiceUtil.updatePortletItem( + userId, groupId, name, portletId, + PortletPreferences.class.getName()); + + plid = 0; + ownerId = portletItem.getPortletItemId(); + } + else if (ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) { + String userUuid = element.attributeValue("user-uuid"); + + ownerId = portletDataContext.getUserId(userUuid); + } + + if (defaultUser) { + ownerId = defaultUserId; + } + + xml = checkPortletPreferences( + portletDataContext, companyId, ownerId, ownerType, plid, + portletId, xml); + + PortletPreferencesLocalServiceUtil.updatePreferences( + ownerId, ownerType, plid, portletId, xml); + } + } + + if (preserveScopeLayoutId && (layout != null)) { + javax.portlet.PortletPreferences jxPreferences = + PortletPreferencesFactoryUtil.getLayoutPortletSetup( + layout, portletId); + + try { + jxPreferences.setValue("lfrScopeType", scopeType); + jxPreferences.setValue("lfrScopeLayoutUuid", scopeLayoutUuid); + + jxPreferences.store(); + } + finally { + portletDataContext.setScopeType(scopeType); + portletDataContext.setScopeLayoutUuid(scopeLayoutUuid); + } + } + } + + protected void readAssetCategories(PortletDataContext portletDataContext) + throws Exception { + + String xml = portletDataContext.getZipEntryAsString( + portletDataContext.getSourceRootPath() + + "/categories-hierarchy.xml"); + + if (xml == null) { + return; + } + + Document document = SAXReaderUtil.read(xml); + + Element rootElement = document.getRootElement(); + + Element assetVocabulariesElement = rootElement.element("vocabularies"); + + List assetVocabularyElements = + assetVocabulariesElement.elements("vocabulary"); + + Map assetVocabularyPKs = + (Map)portletDataContext.getNewPrimaryKeysMap( + AssetVocabulary.class); + + for (Element assetVocabularyElement : assetVocabularyElements) { + String path = assetVocabularyElement.attributeValue("path"); + + if (!portletDataContext.isPathNotProcessed(path)) { + continue; + } + + AssetVocabulary assetVocabulary = + (AssetVocabulary)portletDataContext.getZipEntryAsObject(path); + + importAssetVocabulary( + portletDataContext, assetVocabularyPKs, assetVocabularyElement, + assetVocabulary); + } + + Element assetCategoriesElement = rootElement.element("categories"); + + List assetCategoryElements = assetCategoriesElement.elements( + "category"); + + Map assetCategoryPKs = + (Map)portletDataContext.getNewPrimaryKeysMap( + AssetCategory.class); + + Map assetCategoryUuids = + (Map)portletDataContext.getNewPrimaryKeysMap( + AssetCategory.class.getName() + "uuid"); + + for (Element assetCategoryElement : assetCategoryElements) { + String path = assetCategoryElement.attributeValue("path"); + + if (!portletDataContext.isPathNotProcessed(path)) { + continue; + } + + AssetCategory assetCategory = + (AssetCategory)portletDataContext.getZipEntryAsObject(path); + + importAssetCategory( + portletDataContext, assetVocabularyPKs, assetCategoryPKs, + assetCategoryUuids, assetCategoryElement, assetCategory); + } + + Element assetsElement = rootElement.element("assets"); + + List assetElements = assetsElement.elements("asset"); + + for (Element assetElement : assetElements) { + String className = GetterUtil.getString( + assetElement.attributeValue("class-name")); + long classPK = GetterUtil.getLong( + assetElement.attributeValue("class-pk")); + String[] assetCategoryUuidArray = StringUtil.split( + GetterUtil.getString( + assetElement.attributeValue("category-uuids"))); + + long[] assetCategoryIds = new long[0]; + + for (String assetCategoryUuid : assetCategoryUuidArray) { + assetCategoryUuid = MapUtil.getString( + assetCategoryUuids, assetCategoryUuid, assetCategoryUuid); + + AssetCategory assetCategory = AssetCategoryUtil.fetchByUUID_G( + assetCategoryUuid, portletDataContext.getScopeGroupId()); + + if (assetCategory == null) { + Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( + portletDataContext.getCompanyId()); + + assetCategory = AssetCategoryUtil.fetchByUUID_G( + assetCategoryUuid, companyGroup.getGroupId()); + } + + if (assetCategory != null) { + assetCategoryIds = ArrayUtil.append( + assetCategoryIds, assetCategory.getCategoryId()); + } + } + + portletDataContext.addAssetCategories( + className, classPK, assetCategoryIds); + } + } + + protected void readAssetLinks(PortletDataContext portletDataContext) + throws Exception { + + String xml = portletDataContext.getZipEntryAsString( + portletDataContext.getSourceRootPath() + "/links.xml"); + + if (xml == null) { + return; + } + + Document document = SAXReaderUtil.read(xml); + + Element rootElement = document.getRootElement(); + + List assetLinkElements = rootElement.elements("asset-link"); + + for (Element assetLinkElement : assetLinkElements) { + String sourceUuid = GetterUtil.getString( + assetLinkElement.attributeValue("source-uuid")); + String[] assetEntryUuidArray = StringUtil.split( + GetterUtil.getString( + assetLinkElement.attributeValue("target-uuids"))); + int assetLinkType = GetterUtil.getInteger( + assetLinkElement.attributeValue("type")); + + List assetEntryIds = new ArrayList(); + + for (String assetEntryUuid : assetEntryUuidArray) { + try { + AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry( + portletDataContext.getScopeGroupId(), assetEntryUuid); + + assetEntryIds.add(assetEntry.getEntryId()); + } + catch (NoSuchEntryException nsee) { + } + } + + if (assetEntryIds.isEmpty()) { + continue; + } + + long[] assetEntryIdsArray = ArrayUtil.toArray( + assetEntryIds.toArray(new Long[assetEntryIds.size()])); + + try { + AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry( + portletDataContext.getScopeGroupId(), sourceUuid); + + AssetLinkLocalServiceUtil.updateLinks( + assetEntry.getUserId(), assetEntry.getEntryId(), + assetEntryIdsArray, assetLinkType); + } + catch (NoSuchEntryException nsee) { + } + } + } + + protected void readAssetTags(PortletDataContext portletDataContext) + throws Exception { + + String xml = portletDataContext.getZipEntryAsString( + portletDataContext.getSourceRootPath() + "/tags.xml"); + + if (xml == null) { + return; + } + + Document document = SAXReaderUtil.read(xml); + + Element rootElement = document.getRootElement(); + + List assetTagElements = rootElement.elements("tag"); + + for (Element assetTagElement : assetTagElements) { + String path = assetTagElement.attributeValue("path"); + + if (!portletDataContext.isPathNotProcessed(path)) { + continue; + } + + AssetTag assetTag = + (AssetTag)portletDataContext.getZipEntryAsObject(path); + + Map assetTagPKs = + (Map)portletDataContext.getNewPrimaryKeysMap( + AssetTag.class); + + importAssetTag( + portletDataContext, assetTagPKs, assetTagElement, assetTag); + } + + List assetElements = rootElement.elements("asset"); + + for (Element assetElement : assetElements) { + String className = GetterUtil.getString( + assetElement.attributeValue("class-name")); + long classPK = GetterUtil.getLong( + assetElement.attributeValue("class-pk")); + String assetTagNames = GetterUtil.getString( + assetElement.attributeValue("tags")); + + portletDataContext.addAssetTags( + className, classPK, StringUtil.split(assetTagNames)); + } + } + + protected void readComments(PortletDataContext portletDataContext) + throws Exception { + + String xml = portletDataContext.getZipEntryAsString( + portletDataContext.getSourceRootPath() + "/comments.xml"); + + if (xml == null) { + return; + } + + Document document = SAXReaderUtil.read(xml); + + Element rootElement = document.getRootElement(); + + List assetElements = rootElement.elements("asset"); + + for (Element assetElement : assetElements) { + String path = assetElement.attributeValue("path"); + String className = assetElement.attributeValue("class-name"); + long classPK = GetterUtil.getLong( + assetElement.attributeValue("class-pk")); + + List zipFolderEntries = + portletDataContext.getZipFolderEntries(path); + + List mbMessages = new ArrayList(); + + for (String zipFolderEntry : zipFolderEntries) { + MBMessage mbMessage = + (MBMessage)portletDataContext.getZipEntryAsObject( + zipFolderEntry); + + if (mbMessage != null) { + mbMessages.add(mbMessage); + } + } + + portletDataContext.addComments(className, classPK, mbMessages); + } + } + + protected void readExpandoTables(PortletDataContext portletDataContext) + throws Exception { + + String xml = portletDataContext.getZipEntryAsString( + portletDataContext.getSourceRootPath() + "/expando-tables.xml"); + + if (xml == null) { + return; + } + + Document document = SAXReaderUtil.read(xml); + + Element rootElement = document.getRootElement(); + + List expandoTableElements = rootElement.elements( + "expando-table"); + + for (Element expandoTableElement : expandoTableElements) { + String className = expandoTableElement.attributeValue("class-name"); + + ExpandoTable expandoTable = null; + + try { + expandoTable = ExpandoTableLocalServiceUtil.getDefaultTable( + portletDataContext.getCompanyId(), className); + } + catch (NoSuchTableException nste) { + expandoTable = ExpandoTableLocalServiceUtil.addDefaultTable( + portletDataContext.getCompanyId(), className); + } + + List expandoColumnElements = expandoTableElement.elements( + "expando-column"); + + for (Element expandoColumnElement : expandoColumnElements) { + long columnId = GetterUtil.getLong( + expandoColumnElement.attributeValue("column-id")); + String name = expandoColumnElement.attributeValue("name"); + int type = GetterUtil.getInteger( + expandoColumnElement.attributeValue("type")); + String defaultData = expandoColumnElement.elementText( + "default-data"); + String typeSettings = expandoColumnElement.elementText( + "type-settings"); + + Serializable defaultDataObject = + ExpandoConverterUtil.getAttributeFromString( + type, defaultData); + + ExpandoColumn expandoColumn = + ExpandoColumnLocalServiceUtil.getColumn( + expandoTable.getTableId(), name); + + if (expandoColumn != null) { + ExpandoColumnLocalServiceUtil.updateColumn( + expandoColumn.getColumnId(), name, type, + defaultDataObject); + } + else { + expandoColumn = ExpandoColumnLocalServiceUtil.addColumn( + expandoTable.getTableId(), name, type, + defaultDataObject); + } + + ExpandoColumnLocalServiceUtil.updateTypeSettings( + expandoColumn.getColumnId(), typeSettings); + + portletDataContext.importPermissions( + ExpandoColumn.class, columnId, expandoColumn.getColumnId()); + } + } + } + + protected void readLocks(PortletDataContext portletDataContext) + throws Exception { + + String xml = portletDataContext.getZipEntryAsString( + portletDataContext.getSourceRootPath() + "/locks.xml"); + + if (xml == null) { + return; + } + + Document document = SAXReaderUtil.read(xml); + + Element rootElement = document.getRootElement(); + + List assetElements = rootElement.elements("asset"); + + for (Element assetElement : assetElements) { + String path = assetElement.attributeValue("path"); + String className = assetElement.attributeValue("class-name"); + String key = assetElement.attributeValue("key"); + + Lock lock = (Lock)portletDataContext.getZipEntryAsObject(path); + + if (lock != null) { + portletDataContext.addLocks(className, key, lock); + } + } + } + + protected void readRatingsEntries(PortletDataContext portletDataContext) + throws Exception { + + String xml = portletDataContext.getZipEntryAsString( + portletDataContext.getSourceRootPath() + "/ratings.xml"); + + if (xml == null) { + return; + } + + Document document = SAXReaderUtil.read(xml); + + Element rootElement = document.getRootElement(); + + List assetElements = rootElement.elements("asset"); + + for (Element assetElement : assetElements) { + String path = assetElement.attributeValue("path"); + String className = assetElement.attributeValue("class-name"); + long classPK = GetterUtil.getLong( + assetElement.attributeValue("class-pk")); + + List zipFolderEntries = + portletDataContext.getZipFolderEntries(path); + + List ratingsEntries = new ArrayList(); + + for (String zipFolderEntry : zipFolderEntries) { + RatingsEntry ratingsEntry = + (RatingsEntry)portletDataContext.getZipEntryAsObject( + zipFolderEntry); + + if (ratingsEntry != null) { + ratingsEntries.add(ratingsEntry); + } + } + + portletDataContext.addRatingsEntries( + className, classPK, ratingsEntries); + } + } + + protected void resetPortletScope( + PortletDataContext portletDataContext, long groupId) { + + portletDataContext.setScopeGroupId(groupId); + portletDataContext.setScopeLayoutUuid(StringPool.BLANK); + portletDataContext.setScopeType(StringPool.BLANK); + } + + protected void setPortletScope( + PortletDataContext portletDataContext, Element portletElement) { + + // Portlet data scope + + String scopeLayoutUuid = GetterUtil.getString( + portletElement.attributeValue("scope-layout-uuid")); + String scopeLayoutType = GetterUtil.getString( + portletElement.attributeValue("scope-layout-type")); + + portletDataContext.setScopeLayoutUuid(scopeLayoutUuid); + portletDataContext.setScopeType(scopeLayoutType); + + // Layout scope + + try { + Group scopeGroup = null; + + if (scopeLayoutType.equals("company")) { + scopeGroup = GroupLocalServiceUtil.getCompanyGroup( + portletDataContext.getCompanyId()); + } + else if (Validator.isNotNull(scopeLayoutUuid)) { + Layout scopeLayout = + LayoutLocalServiceUtil.getLayoutByUuidAndGroupId( + scopeLayoutUuid, portletDataContext.getGroupId()); + + if (scopeLayout.hasScopeGroup()) { + scopeGroup = scopeLayout.getScopeGroup(); + } + else { + String name = String.valueOf(scopeLayout.getPlid()); + + scopeGroup = GroupLocalServiceUtil.addGroup( + portletDataContext.getUserId(null), + Layout.class.getName(), scopeLayout.getPlid(), name, + null, 0, null, false, true, null); + } + + Group group = scopeLayout.getGroup(); + + if (group.isStaged() && !group.isStagedRemotely()) { + try { + Layout oldLayout = + LayoutLocalServiceUtil.getLayoutByUuidAndGroupId( + scopeLayoutUuid, + portletDataContext.getSourceGroupId()); + + Group oldScopeGroup = oldLayout.getScopeGroup(); + + oldScopeGroup.setLiveGroupId(scopeGroup.getGroupId()); + + GroupLocalServiceUtil.updateGroup(oldScopeGroup, true); + } + catch (NoSuchLayoutException nsle) { + if (_log.isWarnEnabled()) { + _log.warn(nsle); + } + } + } + + portletDataContext.setScopeGroupId(scopeGroup.getGroupId()); + } + } + catch (PortalException pe) { + } + catch (Exception e) { + _log.error(e, e); + } + } + + private static Log _log = LogFactoryUtil.getLog(PortletImporter.class); + + private PermissionImporter _permissionImporter = new PermissionImporter(); + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portal/model/impl/ImageImpl.java b/portal-impl/src/com/liferay/portal/model/impl/ImageImpl.java index 38b19d6c394b5d..985710f8760453 100644 --- a/portal-impl/src/com/liferay/portal/model/impl/ImageImpl.java +++ b/portal-impl/src/com/liferay/portal/model/impl/ImageImpl.java @@ -55,8 +55,7 @@ public byte[] getTextObj() { } else { is = DLStoreUtil.getFileAsStream( - _DEFAULT_COMPANY_ID, _DEFAULT_REPOSITORY_ID, - getFileName()); + _DEFAULT_COMPANY_ID, _DEFAULT_REPOSITORY_ID, getFileName()); } byte[] bytes = FileUtil.getBytes(is); diff --git a/portal-impl/src/com/liferay/portal/notifications/ChannelImpl.java b/portal-impl/src/com/liferay/portal/notifications/ChannelImpl.java index e3e4a16ecf2170..ed027732e7e88b 100644 --- a/portal-impl/src/com/liferay/portal/notifications/ChannelImpl.java +++ b/portal-impl/src/com/liferay/portal/notifications/ChannelImpl.java @@ -150,8 +150,7 @@ public void deleteUserNotificiationEvent(String notificationEventUuid) } catch (Exception e) { throw new ChannelException( - "Uanble to delete event " + notificationEventUuid , - e); + "Uanble to delete event " + notificationEventUuid , e); } } diff --git a/portal-impl/src/com/liferay/portal/poller/PollerRequestHandlerImpl.java b/portal-impl/src/com/liferay/portal/poller/PollerRequestHandlerImpl.java index ffc02b8af78935..f434c3c82bdffe 100644 --- a/portal-impl/src/com/liferay/portal/poller/PollerRequestHandlerImpl.java +++ b/portal-impl/src/com/liferay/portal/poller/PollerRequestHandlerImpl.java @@ -1,440 +1,435 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portal.poller; - -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.json.JSONFactoryUtil; -import com.liferay.portal.kernel.json.JSONObject; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.messaging.DestinationNames; -import com.liferay.portal.kernel.messaging.Message; -import com.liferay.portal.kernel.messaging.MessageBusUtil; -import com.liferay.portal.kernel.messaging.MessageListener; -import com.liferay.portal.kernel.poller.DefaultPollerResponse; -import com.liferay.portal.kernel.poller.PollerHeader; -import com.liferay.portal.kernel.poller.PollerProcessor; -import com.liferay.portal.kernel.poller.PollerRequest; -import com.liferay.portal.kernel.poller.PollerResponse; -import com.liferay.portal.kernel.util.GetterUtil; -import com.liferay.portal.kernel.util.StringPool; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.kernel.uuid.PortalUUIDUtil; -import com.liferay.portal.model.BrowserTracker; -import com.liferay.portal.model.Company; -import com.liferay.portal.service.BrowserTrackerLocalServiceUtil; -import com.liferay.portal.service.CompanyLocalServiceUtil; -import com.liferay.util.Encryptor; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * @author Michael C. Han - * @author Brian Wing Shun Chan - * @author Edward Han - */ -public class PollerRequestHandlerImpl - implements PollerRequestHandler, MessageListener { - - public PollerHeader getPollerHeader(String pollerRequestString) { - if (Validator.isNull(pollerRequestString)) { - return null; - } - - Map[] pollerRequestChunks = - parsePollerRequestParameters(pollerRequestString); - - return parsePollerRequestHeader(pollerRequestChunks); - } - - public JSONObject processRequest(String path, String pollerRequestString) - throws Exception { - - if (Validator.isNull(pollerRequestString)) { - return null; - } - - Map[] pollerRequestChunks = - parsePollerRequestParameters(pollerRequestString); - - PollerHeader pollerHeader = parsePollerRequestHeader( - pollerRequestChunks); - - if (pollerHeader == null) { - return null; - } - - boolean receiveRequest = isReceiveRequest(path); - - String pollerSessionId = getPollerSessionId(pollerHeader); - - PollerSession pollerSession = null; - - synchronized (_pollerSessions) { - pollerSession = _pollerSessions.get(pollerSessionId); - - if ((pollerSession == null) && receiveRequest) { - pollerSession = new PollerSession(pollerSessionId); - - _pollerSessions.put(pollerSessionId, pollerSession); - } - } - - List pollerRequests = createPollerRequests( - pollerHeader, pollerRequestChunks, receiveRequest); - - executePollerRequests(pollerSession, pollerRequests); - - if (receiveRequest) { - return createPollerResponseHeader(pollerHeader); - } - else { - return null; - } - } - - public void receive(Message message) { - Object messagePayload = message.getPayload(); - - if (!(messagePayload instanceof PollerResponse)) { - return; - } - - PollerResponse pollerResponse = (PollerResponse) messagePayload; - - PollerHeader pollerHeader = pollerResponse.getPollerHeader(); - - String pollerSessionId = getPollerSessionId(pollerHeader); - - synchronized (_pollerSessions) { - PollerSession pollerSession = _pollerSessions.get(pollerSessionId); - - if ((pollerSession != null) && - pollerSession.completePortletProcessing( - pollerResponse.getPortletId(), message.getResponseId())) { - - _pollerSessions.remove(pollerSessionId); - } - } - } - - protected PollerRequest createPollerRequest( - boolean receiveRequest, PollerHeader pollerHeader, String portletId) - throws Exception { - - return createPollerRequest( - receiveRequest, pollerHeader, portletId, - new HashMap(), null); - } - - protected PollerRequest createPollerRequest( - boolean receiveRequest, PollerHeader pollerHeader, String portletId, - Map parameterMap, String chunkId) - throws Exception { - - PollerProcessor pollerProcessor = - PollerProcessorUtil.getPollerProcessor(portletId); - - if (pollerProcessor == null) { - if (_log.isWarnEnabled()) { - _log.warn( - "Poller processor not found for portlet " + portletId); - } - - return null; - } - - return new PollerRequest( - pollerHeader, portletId, parameterMap, chunkId, receiveRequest); - } - - protected List createPollerRequests( - PollerHeader pollerHeader, - Map[] pollerRequestChunks, boolean receiveRequest) - throws Exception { - - String[] portletIds = pollerHeader.getPortletIds(); - - List pollerRequests = new ArrayList( - portletIds.length); - - Set receiveRequestPortletIds = null; - - if (receiveRequest) { - receiveRequestPortletIds = new HashSet( - (int)(pollerRequestChunks.length / 0.75) + 1); - } - - for (int i = 1; i < pollerRequestChunks.length; i++) { - Map pollerRequestChunk = pollerRequestChunks[i]; - - String portletId = (String)pollerRequestChunk.get("portletId"); - Map parameterMap = parseData(pollerRequestChunk); - String chunkId = (String)pollerRequestChunk.get("chunkId"); - - try { - PollerRequest pollerRequest = createPollerRequest( - receiveRequest, pollerHeader, portletId, parameterMap, - chunkId); - - pollerRequests.add(pollerRequest); - - if (receiveRequest) { - receiveRequestPortletIds.add(portletId); - } - } - catch (Exception e) { - _log.error(e, e); - } - } - - if (receiveRequest) { - for (String portletId : portletIds) { - if (receiveRequestPortletIds.contains(portletId)) { - continue; - } - - try { - PollerRequest pollerRequest = createPollerRequest( - receiveRequest, pollerHeader, portletId); - - pollerRequests.add(pollerRequest); - } - catch (Exception e) { - _log.error(e, e); - } - } - } - - return pollerRequests; - } - - protected JSONObject createPollerResponseHeader(PollerHeader pollerHeader) - throws SystemException { - - if (pollerHeader == null) { - return null; - } - - boolean suspendPolling = false; - - if (pollerHeader.isStartPolling()) { - BrowserTrackerLocalServiceUtil.updateBrowserTracker( - pollerHeader.getUserId(), pollerHeader.getBrowserKey()); - } - else { - BrowserTracker browserTracker = - BrowserTrackerLocalServiceUtil.getBrowserTracker( - pollerHeader.getUserId(), pollerHeader.getBrowserKey()); - - if (browserTracker.getBrowserKey() != - pollerHeader.getBrowserKey()) { - - suspendPolling = true; - } - } - - JSONObject pollerResponseHeaderJSONObject = - JSONFactoryUtil.createJSONObject(); - - pollerResponseHeaderJSONObject.put("userId", pollerHeader.getUserId()); - pollerResponseHeaderJSONObject.put( - "initialRequest", pollerHeader.isInitialRequest()); - pollerResponseHeaderJSONObject.put("suspendPolling", suspendPolling); - - return pollerResponseHeaderJSONObject; - } - - protected void executePollerRequests( - PollerSession pollerSession, List pollerRequests) { - - for (PollerRequest pollerRequest : pollerRequests) { - PollerRequestResponsePair pollerRequestResponsePair = - new PollerRequestResponsePair(pollerRequest); - - String responseId = null; - - if (pollerRequest.isReceiveRequest()) { - responseId = PortalUUIDUtil.generate(); - - PollerResponse pollerResponse = new DefaultPollerResponse( - pollerRequest.getPollerHeader(), - pollerRequest.getPortletId(), - pollerRequest.getChunkId()); - - pollerRequestResponsePair.setPollerResponse(pollerResponse); - - if (!pollerSession.beginPortletProcessing( - pollerRequestResponsePair, responseId)) { - - continue; - } - } - - Message message = new Message(); - - message.setPayload(pollerRequestResponsePair); - - if (pollerRequest.isReceiveRequest()) { - message.setResponseId(responseId); - - message.setResponseDestinationName( - DestinationNames.POLLER_RESPONSE); - } - - MessageBusUtil.sendMessage(DestinationNames.POLLER, message); - } - } - - protected String fixPollerRequestString(String pollerRequestString) { - if (Validator.isNull(pollerRequestString)) { - return null; - } - - return StringUtil.replace( - pollerRequestString, - new String[] { - StringPool.OPEN_CURLY_BRACE, - StringPool.CLOSE_CURLY_BRACE, - _ESCAPED_OPEN_CURLY_BRACE, - _ESCAPED_CLOSE_CURLY_BRACE - }, - new String[] { - _OPEN_HASH_MAP_WRAPPER, - StringPool.DOUBLE_CLOSE_CURLY_BRACE, - StringPool.OPEN_CURLY_BRACE, - StringPool.CLOSE_CURLY_BRACE - }); - } - - protected String getPollerSessionId(PollerHeader pollerHeader) { - return String.valueOf(pollerHeader.getUserId()); - } - - protected long getUserId(long companyId, String userIdString) { - long userId = 0; - - try { - Company company = CompanyLocalServiceUtil.getCompany(companyId); - - userId = GetterUtil.getLong( - Encryptor.decrypt(company.getKeyObj(), userIdString)); - } - catch (Exception e) { - _log.error( - "Invalid credentials for company id " + companyId + - " and user id " + userIdString); - } - - return userId; - } - - protected boolean isReceiveRequest(String path) { - if ((path != null) && path.endsWith(_PATH_RECEIVE)) { - return true; - } - else { - return false; - } - } - - protected Map parseData( - Map pollerRequestChunk) - throws Exception { - - Map oldParameterMap = - (Map)pollerRequestChunk.get("data"); - - Map newParameterMap = new HashMap(); - - if (oldParameterMap == null) { - return newParameterMap; - } - - for (Map.Entry entry : oldParameterMap.entrySet()) { - newParameterMap.put( - entry.getKey(), String.valueOf(entry.getValue())); - } - - return newParameterMap; - } - - protected PollerHeader parsePollerRequestHeader( - Map[] pollerRequestChunks) { - - if ((pollerRequestChunks == null) || (pollerRequestChunks.length < 1)) { - return null; - } - - Map pollerRequestChunk = pollerRequestChunks[0]; - - long companyId = GetterUtil.getLong( - String.valueOf(pollerRequestChunk.get("companyId"))); - String userIdString = GetterUtil.getString( - String.valueOf(pollerRequestChunk.get("userId"))); - long browserKey = GetterUtil.getLong( - String.valueOf(pollerRequestChunk.get("browserKey"))); - String[] portletIds = StringUtil.split( - String.valueOf(pollerRequestChunk.get("portletIds"))); - boolean initialRequest = GetterUtil.getBoolean( - String.valueOf(pollerRequestChunk.get("initialRequest"))); - boolean startPolling = GetterUtil.getBoolean( - String.valueOf(pollerRequestChunk.get("startPolling"))); - - long userId = getUserId(companyId, userIdString); - - if (userId == 0) { - return null; - } - - return new PollerHeader( - companyId, userId, browserKey, portletIds, initialRequest, - startPolling); - } - - protected Map[] parsePollerRequestParameters( - String pollerRequestString) { - - String fixedPollerRequestString = fixPollerRequestString( - pollerRequestString); - - return (Map[])JSONFactoryUtil.deserialize( - fixedPollerRequestString); - } - - private static final String _ESCAPED_CLOSE_CURLY_BRACE = - "[$CLOSE_CURLY_BRACE$]"; - - private static final String _ESCAPED_OPEN_CURLY_BRACE = - "[$OPEN_CURLY_BRACE$]"; - - private static final String _OPEN_HASH_MAP_WRAPPER = - "{\"javaClass\":\"java.util.HashMap\",\"map\":{"; - - private static final String _PATH_RECEIVE = "/receive"; - - private static Log _log = LogFactoryUtil.getLog( - PollerRequestHandlerImpl.class); - - private Map _pollerSessions = - new HashMap(); - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portal.poller; + +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.json.JSONFactoryUtil; +import com.liferay.portal.kernel.json.JSONObject; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.messaging.DestinationNames; +import com.liferay.portal.kernel.messaging.Message; +import com.liferay.portal.kernel.messaging.MessageBusUtil; +import com.liferay.portal.kernel.messaging.MessageListener; +import com.liferay.portal.kernel.poller.DefaultPollerResponse; +import com.liferay.portal.kernel.poller.PollerHeader; +import com.liferay.portal.kernel.poller.PollerProcessor; +import com.liferay.portal.kernel.poller.PollerRequest; +import com.liferay.portal.kernel.poller.PollerResponse; +import com.liferay.portal.kernel.util.GetterUtil; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.kernel.uuid.PortalUUIDUtil; +import com.liferay.portal.model.BrowserTracker; +import com.liferay.portal.model.Company; +import com.liferay.portal.service.BrowserTrackerLocalServiceUtil; +import com.liferay.portal.service.CompanyLocalServiceUtil; +import com.liferay.util.Encryptor; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author Michael C. Han + * @author Brian Wing Shun Chan + * @author Edward Han + */ +public class PollerRequestHandlerImpl + implements PollerRequestHandler, MessageListener { + + public PollerHeader getPollerHeader(String pollerRequestString) { + if (Validator.isNull(pollerRequestString)) { + return null; + } + + Map[] pollerRequestChunks = + parsePollerRequestParameters(pollerRequestString); + + return parsePollerRequestHeader(pollerRequestChunks); + } + + public JSONObject processRequest(String path, String pollerRequestString) + throws Exception { + + if (Validator.isNull(pollerRequestString)) { + return null; + } + + Map[] pollerRequestChunks = + parsePollerRequestParameters(pollerRequestString); + + PollerHeader pollerHeader = parsePollerRequestHeader( + pollerRequestChunks); + + if (pollerHeader == null) { + return null; + } + + boolean receiveRequest = isReceiveRequest(path); + + String pollerSessionId = getPollerSessionId(pollerHeader); + + PollerSession pollerSession = null; + + synchronized (_pollerSessions) { + pollerSession = _pollerSessions.get(pollerSessionId); + + if ((pollerSession == null) && receiveRequest) { + pollerSession = new PollerSession(pollerSessionId); + + _pollerSessions.put(pollerSessionId, pollerSession); + } + } + + List pollerRequests = createPollerRequests( + pollerHeader, pollerRequestChunks, receiveRequest); + + executePollerRequests(pollerSession, pollerRequests); + + if (receiveRequest) { + return createPollerResponseHeader(pollerHeader); + } + else { + return null; + } + } + + public void receive(Message message) { + Object messagePayload = message.getPayload(); + + if (!(messagePayload instanceof PollerResponse)) { + return; + } + + PollerResponse pollerResponse = (PollerResponse) messagePayload; + + PollerHeader pollerHeader = pollerResponse.getPollerHeader(); + + String pollerSessionId = getPollerSessionId(pollerHeader); + + synchronized (_pollerSessions) { + PollerSession pollerSession = _pollerSessions.get(pollerSessionId); + + if ((pollerSession != null) && + pollerSession.completePortletProcessing( + pollerResponse.getPortletId(), message.getResponseId())) { + + _pollerSessions.remove(pollerSessionId); + } + } + } + + protected PollerRequest createPollerRequest( + boolean receiveRequest, PollerHeader pollerHeader, String portletId) + throws Exception { + + return createPollerRequest( + receiveRequest, pollerHeader, portletId, + new HashMap(), null); + } + + protected PollerRequest createPollerRequest( + boolean receiveRequest, PollerHeader pollerHeader, String portletId, + Map parameterMap, String chunkId) + throws Exception { + + PollerProcessor pollerProcessor = + PollerProcessorUtil.getPollerProcessor(portletId); + + if (pollerProcessor == null) { + if (_log.isWarnEnabled()) { + _log.warn( + "Poller processor not found for portlet " + portletId); + } + + return null; + } + + return new PollerRequest( + pollerHeader, portletId, parameterMap, chunkId, receiveRequest); + } + + protected List createPollerRequests( + PollerHeader pollerHeader, + Map[] pollerRequestChunks, boolean receiveRequest) + throws Exception { + + String[] portletIds = pollerHeader.getPortletIds(); + + List pollerRequests = new ArrayList( + portletIds.length); + + Set receiveRequestPortletIds = null; + + if (receiveRequest) { + receiveRequestPortletIds = new HashSet( + (int)(pollerRequestChunks.length / 0.75) + 1); + } + + for (int i = 1; i < pollerRequestChunks.length; i++) { + Map pollerRequestChunk = pollerRequestChunks[i]; + + String portletId = (String)pollerRequestChunk.get("portletId"); + Map parameterMap = parseData(pollerRequestChunk); + String chunkId = (String)pollerRequestChunk.get("chunkId"); + + try { + PollerRequest pollerRequest = createPollerRequest( + receiveRequest, pollerHeader, portletId, parameterMap, + chunkId); + + pollerRequests.add(pollerRequest); + + if (receiveRequest) { + receiveRequestPortletIds.add(portletId); + } + } + catch (Exception e) { + _log.error(e, e); + } + } + + if (receiveRequest) { + for (String portletId : portletIds) { + if (receiveRequestPortletIds.contains(portletId)) { + continue; + } + + try { + PollerRequest pollerRequest = createPollerRequest( + receiveRequest, pollerHeader, portletId); + + pollerRequests.add(pollerRequest); + } + catch (Exception e) { + _log.error(e, e); + } + } + } + + return pollerRequests; + } + + protected JSONObject createPollerResponseHeader(PollerHeader pollerHeader) + throws SystemException { + + if (pollerHeader == null) { + return null; + } + + boolean suspendPolling = false; + + if (pollerHeader.isStartPolling()) { + BrowserTrackerLocalServiceUtil.updateBrowserTracker( + pollerHeader.getUserId(), pollerHeader.getBrowserKey()); + } + else { + BrowserTracker browserTracker = + BrowserTrackerLocalServiceUtil.getBrowserTracker( + pollerHeader.getUserId(), pollerHeader.getBrowserKey()); + + if (browserTracker.getBrowserKey() != + pollerHeader.getBrowserKey()) { + + suspendPolling = true; + } + } + + JSONObject pollerResponseHeaderJSONObject = + JSONFactoryUtil.createJSONObject(); + + pollerResponseHeaderJSONObject.put("userId", pollerHeader.getUserId()); + pollerResponseHeaderJSONObject.put( + "initialRequest", pollerHeader.isInitialRequest()); + pollerResponseHeaderJSONObject.put("suspendPolling", suspendPolling); + + return pollerResponseHeaderJSONObject; + } + + protected void executePollerRequests( + PollerSession pollerSession, List pollerRequests) { + + for (PollerRequest pollerRequest : pollerRequests) { + PollerRequestResponsePair pollerRequestResponsePair = + new PollerRequestResponsePair(pollerRequest); + + String responseId = null; + + if (pollerRequest.isReceiveRequest()) { + responseId = PortalUUIDUtil.generate(); + + PollerResponse pollerResponse = new DefaultPollerResponse( + pollerRequest.getPollerHeader(), + pollerRequest.getPortletId(), pollerRequest.getChunkId()); + + pollerRequestResponsePair.setPollerResponse(pollerResponse); + + if (!pollerSession.beginPortletProcessing( + pollerRequestResponsePair, responseId)) { + + continue; + } + } + + Message message = new Message(); + + message.setPayload(pollerRequestResponsePair); + + if (pollerRequest.isReceiveRequest()) { + message.setResponseId(responseId); + + message.setResponseDestinationName( + DestinationNames.POLLER_RESPONSE); + } + + MessageBusUtil.sendMessage(DestinationNames.POLLER, message); + } + } + + protected String fixPollerRequestString(String pollerRequestString) { + if (Validator.isNull(pollerRequestString)) { + return null; + } + + return StringUtil.replace( + pollerRequestString, + new String[] { + StringPool.OPEN_CURLY_BRACE, StringPool.CLOSE_CURLY_BRACE, + _ESCAPED_OPEN_CURLY_BRACE, _ESCAPED_CLOSE_CURLY_BRACE + }, + new String[] { + _OPEN_HASH_MAP_WRAPPER, StringPool.DOUBLE_CLOSE_CURLY_BRACE, + StringPool.OPEN_CURLY_BRACE, StringPool.CLOSE_CURLY_BRACE + }); + } + + protected String getPollerSessionId(PollerHeader pollerHeader) { + return String.valueOf(pollerHeader.getUserId()); + } + + protected long getUserId(long companyId, String userIdString) { + long userId = 0; + + try { + Company company = CompanyLocalServiceUtil.getCompany(companyId); + + userId = GetterUtil.getLong( + Encryptor.decrypt(company.getKeyObj(), userIdString)); + } + catch (Exception e) { + _log.error( + "Invalid credentials for company id " + companyId + + " and user id " + userIdString); + } + + return userId; + } + + protected boolean isReceiveRequest(String path) { + if ((path != null) && path.endsWith(_PATH_RECEIVE)) { + return true; + } + else { + return false; + } + } + + protected Map parseData( + Map pollerRequestChunk) + throws Exception { + + Map oldParameterMap = + (Map)pollerRequestChunk.get("data"); + + Map newParameterMap = new HashMap(); + + if (oldParameterMap == null) { + return newParameterMap; + } + + for (Map.Entry entry : oldParameterMap.entrySet()) { + newParameterMap.put( + entry.getKey(), String.valueOf(entry.getValue())); + } + + return newParameterMap; + } + + protected PollerHeader parsePollerRequestHeader( + Map[] pollerRequestChunks) { + + if ((pollerRequestChunks == null) || (pollerRequestChunks.length < 1)) { + return null; + } + + Map pollerRequestChunk = pollerRequestChunks[0]; + + long companyId = GetterUtil.getLong( + String.valueOf(pollerRequestChunk.get("companyId"))); + String userIdString = GetterUtil.getString( + String.valueOf(pollerRequestChunk.get("userId"))); + long browserKey = GetterUtil.getLong( + String.valueOf(pollerRequestChunk.get("browserKey"))); + String[] portletIds = StringUtil.split( + String.valueOf(pollerRequestChunk.get("portletIds"))); + boolean initialRequest = GetterUtil.getBoolean( + String.valueOf(pollerRequestChunk.get("initialRequest"))); + boolean startPolling = GetterUtil.getBoolean( + String.valueOf(pollerRequestChunk.get("startPolling"))); + + long userId = getUserId(companyId, userIdString); + + if (userId == 0) { + return null; + } + + return new PollerHeader( + companyId, userId, browserKey, portletIds, initialRequest, + startPolling); + } + + protected Map[] parsePollerRequestParameters( + String pollerRequestString) { + + String fixedPollerRequestString = fixPollerRequestString( + pollerRequestString); + + return (Map[])JSONFactoryUtil.deserialize( + fixedPollerRequestString); + } + + private static final String _ESCAPED_CLOSE_CURLY_BRACE = + "[$CLOSE_CURLY_BRACE$]"; + + private static final String _ESCAPED_OPEN_CURLY_BRACE = + "[$OPEN_CURLY_BRACE$]"; + + private static final String _OPEN_HASH_MAP_WRAPPER = + "{\"javaClass\":\"java.util.HashMap\",\"map\":{"; + + private static final String _PATH_RECEIVE = "/receive"; + + private static Log _log = LogFactoryUtil.getLog( + PollerRequestHandlerImpl.class); + + private Map _pollerSessions = + new HashMap(); + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portal/repository/cmis/CMISAtomPubRepository.java b/portal-impl/src/com/liferay/portal/repository/cmis/CMISAtomPubRepository.java index c0ae3b9931aa63..2d3322efc0fc59 100644 --- a/portal-impl/src/com/liferay/portal/repository/cmis/CMISAtomPubRepository.java +++ b/portal-impl/src/com/liferay/portal/repository/cmis/CMISAtomPubRepository.java @@ -49,8 +49,7 @@ public Session getSession() throws PortalException, SystemException { Locale locale = LocaleUtil.getDefault(); parameters.put( - SessionParameter.LOCALE_ISO3166_COUNTRY, - locale.getCountry()); + SessionParameter.LOCALE_ISO3166_COUNTRY, locale.getCountry()); parameters.put( SessionParameter.LOCALE_ISO639_LANGUAGE, locale.getLanguage()); diff --git a/portal-impl/src/com/liferay/portal/repository/cmis/CMISWebServicesRepository.java b/portal-impl/src/com/liferay/portal/repository/cmis/CMISWebServicesRepository.java index d6427d4c51f6a4..8172f44b352ca9 100644 --- a/portal-impl/src/com/liferay/portal/repository/cmis/CMISWebServicesRepository.java +++ b/portal-impl/src/com/liferay/portal/repository/cmis/CMISWebServicesRepository.java @@ -46,8 +46,7 @@ public Session getSession() throws PortalException, SystemException { Locale locale = LocaleUtil.getDefault(); parameters.put( - SessionParameter.LOCALE_ISO3166_COUNTRY, - locale.getCountry()); + SessionParameter.LOCALE_ISO3166_COUNTRY, locale.getCountry()); parameters.put(SessionParameter.LOCALE_ISO639_LANGUAGE, locale.getLanguage()); diff --git a/portal-impl/src/com/liferay/portal/repository/liferayrepository/LiferayRepository.java b/portal-impl/src/com/liferay/portal/repository/liferayrepository/LiferayRepository.java index 9d282701396045..c24483c0249018 100644 --- a/portal-impl/src/com/liferay/portal/repository/liferayrepository/LiferayRepository.java +++ b/portal-impl/src/com/liferay/portal/repository/liferayrepository/LiferayRepository.java @@ -95,8 +95,8 @@ public LiferayRepository( DLFileVersionLocalService dlFileVersionLocalService, DLFileVersionService dlFileVersionService, DLFolderLocalService dlFolderLocalService, - DLFolderService dlFolderService, long folderId, - long fileEntryId, long fileVersionId) { + DLFolderService dlFolderService, long folderId, long fileEntryId, + long fileVersionId) { super( repositoryLocalService, repositoryService, dlAppHelperLocalService, diff --git a/portal-impl/src/com/liferay/portal/repository/search/RepositorySearchQueryBuilderImpl.java b/portal-impl/src/com/liferay/portal/repository/search/RepositorySearchQueryBuilderImpl.java index 27c6ad100c3462..643356f3f76ada 100644 --- a/portal-impl/src/com/liferay/portal/repository/search/RepositorySearchQueryBuilderImpl.java +++ b/portal-impl/src/com/liferay/portal/repository/search/RepositorySearchQueryBuilderImpl.java @@ -167,8 +167,8 @@ protected void addSearchKeywords( } protected void addTerm( - BooleanQuery booleanQuery, SearchContext searchContext, - String field, String value) { + BooleanQuery booleanQuery, SearchContext searchContext, String field, + String value) { if (Validator.isNull(value)) { return; diff --git a/portal-impl/src/com/liferay/portal/search/PortalOpenSearchImpl.java b/portal-impl/src/com/liferay/portal/search/PortalOpenSearchImpl.java index a7477633edca32..6332b483bfbed2 100644 --- a/portal-impl/src/com/liferay/portal/search/PortalOpenSearchImpl.java +++ b/portal-impl/src/com/liferay/portal/search/PortalOpenSearchImpl.java @@ -182,8 +182,8 @@ protected String getJournalURL( if (Validator.isNotNull(article.getLayoutUuid())) { String groupFriendlyURL = PortalUtil.getGroupFriendlyURL( - GroupLocalServiceUtil.getGroup(article.getGroupId()), - false, themeDisplay); + GroupLocalServiceUtil.getGroup(article.getGroupId()), false, + themeDisplay); return groupFriendlyURL.concat( JournalArticleConstants.CANONICAL_URL_SEPARATOR).concat( diff --git a/portal-impl/src/com/liferay/portal/search/SearchPermissionCheckerImpl.java b/portal-impl/src/com/liferay/portal/search/SearchPermissionCheckerImpl.java index e9f87ec3f24655..25472037420a50 100644 --- a/portal-impl/src/com/liferay/portal/search/SearchPermissionCheckerImpl.java +++ b/portal-impl/src/com/liferay/portal/search/SearchPermissionCheckerImpl.java @@ -179,8 +179,7 @@ protected void doAddPermissionFields_5( throws Exception { Resource resource = ResourceLocalServiceUtil.getResource( - companyId, className, ResourceConstants.SCOPE_INDIVIDUAL, - classPK); + companyId, className, ResourceConstants.SCOPE_INDIVIDUAL, classPK); Group group = null; diff --git a/portal-impl/src/com/liferay/portal/search/lucene/LuceneHelperImpl.java b/portal-impl/src/com/liferay/portal/search/lucene/LuceneHelperImpl.java index 14d021b577ff90..599d9dffd89909 100644 --- a/portal-impl/src/com/liferay/portal/search/lucene/LuceneHelperImpl.java +++ b/portal-impl/src/com/liferay/portal/search/lucene/LuceneHelperImpl.java @@ -498,8 +498,7 @@ public Address selectBootupClusterAddress( } ClusterRequest clusterRequest = ClusterRequest.createMulticastRequest( - new MethodHandler(_getLastGenerationMethodKey, companyId), - true); + new MethodHandler(_getLastGenerationMethodKey, companyId), true); FutureClusterResponses futureClusterResponses = ClusterExecutorUtil.execute(clusterRequest); diff --git a/portal-impl/src/com/liferay/portal/search/lucene/LuceneIndexSearcherImpl.java b/portal-impl/src/com/liferay/portal/search/lucene/LuceneIndexSearcherImpl.java index a25a428016441f..0d673b08c4bd31 100644 --- a/portal-impl/src/com/liferay/portal/search/lucene/LuceneIndexSearcherImpl.java +++ b/portal-impl/src/com/liferay/portal/search/lucene/LuceneIndexSearcherImpl.java @@ -504,8 +504,8 @@ protected String getSnippet( protected Hits toHits( org.apache.lucene.search.IndexSearcher indexSearcher, - HitDocs hitDocs, Query query, long startTime, - float searchTime, int start, int end) + HitDocs hitDocs, Query query, long startTime, float searchTime, + int start, int end) throws IOException, ParseException { int length = hitDocs.getTotalHits(); diff --git a/portal-impl/src/com/liferay/portal/security/ldap/DefaultPortalToLDAPConverter.java b/portal-impl/src/com/liferay/portal/security/ldap/DefaultPortalToLDAPConverter.java index cb38bd59def23d..cde529a7293a1a 100644 --- a/portal-impl/src/com/liferay/portal/security/ldap/DefaultPortalToLDAPConverter.java +++ b/portal-impl/src/com/liferay/portal/security/ldap/DefaultPortalToLDAPConverter.java @@ -450,8 +450,8 @@ protected byte[] getUserPortrait(User user) { protected void populateCustomAttributeModifications( Object object, ExpandoBridge expandoBridge, - Map expandoAttributes, - Properties expandoMappings, Modifications modifications) { + Map expandoAttributes, Properties expandoMappings, + Modifications modifications) { if ((expandoAttributes == null) || expandoAttributes.isEmpty()) { return; diff --git a/portal-impl/src/com/liferay/portal/security/ldap/LDAPSettingsUtil.java b/portal-impl/src/com/liferay/portal/security/ldap/LDAPSettingsUtil.java index 76b0c234a4122b..3f563f6efba76c 100644 --- a/portal-impl/src/com/liferay/portal/security/ldap/LDAPSettingsUtil.java +++ b/portal-impl/src/com/liferay/portal/security/ldap/LDAPSettingsUtil.java @@ -54,8 +54,7 @@ public static String getAuthSearchFilter( "@company_id@", "@email_address@", "@screen_name@", "@user_id@" }, new String[] { - String.valueOf(companyId), emailAddress, screenName, - userId + String.valueOf(companyId), emailAddress, screenName, userId }); if (_log.isDebugEnabled()) { diff --git a/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPExporterImpl.java b/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPExporterImpl.java index 2ab1867be136cc..d8482e8ec37ccb 100644 --- a/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPExporterImpl.java +++ b/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPExporterImpl.java @@ -99,8 +99,8 @@ public void exportToLDAP( Modifications modifications = _portalToLDAPConverter.getLDAPContactModifications( - contact, contactExpandoAttributes, - contactMappings, contactExpandoMappings); + contact, contactExpandoAttributes, contactMappings, + contactExpandoMappings); if (modifications == null) { return; diff --git a/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPImporterImpl.java b/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPImporterImpl.java index 61d7a080881ded..7ffc1e34cb1352 100644 --- a/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPImporterImpl.java +++ b/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPImporterImpl.java @@ -847,8 +847,7 @@ protected void importGroups( protected User importUser( long companyId, Attributes attributes, Properties userMappings, Properties userExpandoMappings, Properties contactMappings, - Properties contactExpandoMappings, - String password) + Properties contactExpandoMappings, String password) throws Exception { LDAPUserTransactionThreadLocal.setOriginatesFromLDAP(true); diff --git a/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPUtil.java b/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPUtil.java index d8f3082bd575de..ba827734729317 100644 --- a/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPUtil.java +++ b/portal-impl/src/com/liferay/portal/security/ldap/PortalLDAPUtil.java @@ -705,8 +705,8 @@ public static boolean isUserGroupMember( public static byte[] searchLDAP( long companyId, LdapContext ldapContext, byte[] cookie, - int maxResults, String baseDN, String filter, - String[] attributeIds, List searchResults) + int maxResults, String baseDN, String filter, String[] attributeIds, + List searchResults) throws Exception { SearchControls searchControls = new SearchControls( diff --git a/portal-impl/src/com/liferay/portal/security/permission/InlineSQLHelperImpl.java b/portal-impl/src/com/liferay/portal/security/permission/InlineSQLHelperImpl.java index 3f8ed688685b93..d9e9537869ccfe 100644 --- a/portal-impl/src/com/liferay/portal/security/permission/InlineSQLHelperImpl.java +++ b/portal-impl/src/com/liferay/portal/security/permission/InlineSQLHelperImpl.java @@ -347,15 +347,12 @@ protected String replacePermissionCheckBlocks( permissionWhere = StringUtil.replace( permissionWhere, new String[] { - "[$OWNER_RESOURCE_BLOCK_IDS$]", - "[$USER_ID$]", - "[$USER_ID_FIELD$]", - "[$USER_RESOURCE_BLOCK_IDS$]" + "[$OWNER_RESOURCE_BLOCK_IDS$]", "[$USER_ID$]", + "[$USER_ID_FIELD$]", "[$USER_RESOURCE_BLOCK_IDS$]" }, new String[] { StringUtil.merge(ownerResourceBlockIds), - String.valueOf(permissionChecker.getUserId()), - userIdField, + String.valueOf(permissionChecker.getUserId()), userIdField, StringUtil.merge(userResourceBlockIds) }); } @@ -524,13 +521,10 @@ protected String replacePermissionCheckJoin( permissionJoin = StringUtil.replace( permissionJoin, new String[] { - "[$CLASS_NAME$]", - "[$COMPANY_ID$]", - "[$PRIM_KEYS$]" + "[$CLASS_NAME$]", "[$COMPANY_ID$]", "[$PRIM_KEYS$]" }, new String[] { - className, - String.valueOf(permissionChecker.getCompanyId()), + className, String.valueOf(permissionChecker.getCompanyId()), sb.toString() }); diff --git a/portal-impl/src/com/liferay/portal/security/permission/PermissionCheckerBagImpl.java b/portal-impl/src/com/liferay/portal/security/permission/PermissionCheckerBagImpl.java index 11987bbdc24857..cb929ccf34d33f 100644 --- a/portal-impl/src/com/liferay/portal/security/permission/PermissionCheckerBagImpl.java +++ b/portal-impl/src/com/liferay/portal/security/permission/PermissionCheckerBagImpl.java @@ -158,8 +158,8 @@ protected boolean isGroupAdminImpl( _userId, group.getGroupId(), RoleConstants.SITE_ADMINISTRATOR, true) || UserGroupRoleLocalServiceUtil.hasUserGroupRole( - _userId, group.getGroupId(), - RoleConstants.SITE_OWNER, true)) { + _userId, group.getGroupId(), RoleConstants.SITE_OWNER, + true)) { return true; } diff --git a/portal-impl/src/com/liferay/portal/service/impl/CompanyLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/CompanyLocalServiceImpl.java index 48d19865035557..9e8eb80cfc7351 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/CompanyLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/CompanyLocalServiceImpl.java @@ -1172,8 +1172,7 @@ public void updateSecurity( PropsKeys.COMPANY_SECURITY_STRANGERS_VERIFY, String.valueOf(strangersVerify)); preferences.setValue( - PropsKeys.COMPANY_SECURITY_SITE_LOGO, - String.valueOf(siteLogo)); + PropsKeys.COMPANY_SECURITY_SITE_LOGO, String.valueOf(siteLogo)); preferences.store(); } diff --git a/portal-impl/src/com/liferay/portal/service/impl/EmailAddressLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/EmailAddressLocalServiceImpl.java index 84a2ae0e83ebb9..41afbeb3baa62c 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/EmailAddressLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/EmailAddressLocalServiceImpl.java @@ -168,8 +168,8 @@ protected void validate( } protected void validate( - long emailAddressId, long companyId, long classNameId, - long classPK, String address, int typeId, boolean primary) + long emailAddressId, long companyId, long classNameId, long classPK, + String address, int typeId, boolean primary) throws PortalException, SystemException { if (!Validator.isEmailAddress(address)) { diff --git a/portal-impl/src/com/liferay/portal/service/impl/LayoutLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/LayoutLocalServiceImpl.java index bacfa88d318eb6..806cf75ed63d7e 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/LayoutLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/LayoutLocalServiceImpl.java @@ -1603,8 +1603,8 @@ public Layout updateFriendlyURL(long plid, String friendlyURL) Layout layout = layoutPersistence.findByPrimaryKey(plid); friendlyURL = getFriendlyURL( - layout.getGroupId(), layout.isPrivateLayout(), - layout.getLayoutId(), StringPool.BLANK, friendlyURL); + layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), + StringPool.BLANK, friendlyURL); validateFriendlyURL( layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), @@ -2271,8 +2271,8 @@ public void updateScopedPortletNames( } protected String getFriendlyURL( - long groupId, boolean privateLayout, long layoutId, - String name, String friendlyURL) + long groupId, boolean privateLayout, long layoutId, String name, + String friendlyURL) throws PortalException, SystemException { friendlyURL = getFriendlyURL(friendlyURL); diff --git a/portal-impl/src/com/liferay/portal/service/impl/LayoutPrototypeServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/LayoutPrototypeServiceImpl.java index b702814d03146a..289c753ffd352c 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/LayoutPrototypeServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/LayoutPrototypeServiceImpl.java @@ -37,8 +37,7 @@ public class LayoutPrototypeServiceImpl extends LayoutPrototypeServiceBaseImpl { public LayoutPrototype addLayoutPrototype( - Map nameMap, String description, - boolean active) + Map nameMap, String description, boolean active) throws PortalException, SystemException { PortalPermissionUtil.check( diff --git a/portal-impl/src/com/liferay/portal/service/impl/LayoutRevisionLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/LayoutRevisionLocalServiceImpl.java index 3afa85f532873b..44ae493123f644 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/LayoutRevisionLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/LayoutRevisionLocalServiceImpl.java @@ -314,8 +314,8 @@ public List getLayoutRevisions( } public List getLayoutRevisions( - long layoutSetBranchId, long layoutBranchId, long plid, - int start, int end, OrderByComparator orderByComparator) + long layoutSetBranchId, long layoutBranchId, long plid, int start, + int end, OrderByComparator orderByComparator) throws SystemException { return layoutRevisionPersistence.findByL_L_P( @@ -448,8 +448,8 @@ public LayoutRevision updateLayoutRevision( // Workflow WorkflowHandlerRegistryUtil.startWorkflowInstance( - layoutRevision.getCompanyId(), layoutRevision.getGroupId(), - userId, LayoutRevision.class.getName(), + layoutRevision.getCompanyId(), layoutRevision.getGroupId(), userId, + LayoutRevision.class.getName(), layoutRevision.getLayoutRevisionId(), layoutRevision, serviceContext); diff --git a/portal-impl/src/com/liferay/portal/service/impl/LayoutServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/LayoutServiceImpl.java index 99dc458911e5d9..bbcc011306fae3 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/LayoutServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/LayoutServiceImpl.java @@ -200,8 +200,8 @@ public Layout addLayout( return addLayout( groupId, privateLayout, parentLayoutId, localeNamesMap, new HashMap(), new HashMap(), - new HashMap(), new HashMap(), - type, hidden, friendlyURL, serviceContext); + new HashMap(), new HashMap(), type, + hidden, friendlyURL, serviceContext); } /** @@ -756,8 +756,7 @@ public void schedulePublishToLive( String jobName = PortalUUIDUtil.generate(); Trigger trigger = new CronTrigger( - jobName, groupName, schedulerStartDate, schedulerEndDate, - cronText); + jobName, groupName, schedulerStartDate, schedulerEndDate, cronText); String command = StringPool.BLANK; diff --git a/portal-impl/src/com/liferay/portal/service/impl/LayoutSetBranchLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/LayoutSetBranchLocalServiceImpl.java index b1d8ac11a01498..8e5c687b6495b4 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/LayoutSetBranchLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/LayoutSetBranchLocalServiceImpl.java @@ -220,8 +220,7 @@ else if (copyLayoutSetBranchId > 0) { serviceContext); layoutRevisionLocalService.addLayoutRevision( - userId, layoutSetBranchId, - layoutBranch.getLayoutBranchId(), + userId, layoutSetBranchId, layoutBranch.getLayoutBranchId(), LayoutRevisionConstants.DEFAULT_PARENT_LAYOUT_REVISION_ID, true, layoutRevision.getPlid(), layoutRevision.getLayoutRevisionId(), diff --git a/portal-impl/src/com/liferay/portal/service/impl/LayoutSetLocalServiceStagingAdvice.java b/portal-impl/src/com/liferay/portal/service/impl/LayoutSetLocalServiceStagingAdvice.java index eba25b27bea205..7474b02d058cdc 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/LayoutSetLocalServiceStagingAdvice.java +++ b/portal-impl/src/com/liferay/portal/service/impl/LayoutSetLocalServiceStagingAdvice.java @@ -80,9 +80,9 @@ else if (methodName.equals("updateLookAndFeel") && (arguments.length == 6)) { returnValue = updateLookAndFeel( - (Long)arguments[0], (Boolean)arguments[1], - (String)arguments[2], (String)arguments[3], - (String)arguments[4], (Boolean)arguments[5]); + (Long)arguments[0], (Boolean)arguments[1], (String)arguments[2], + (String)arguments[3], (String)arguments[4], + (Boolean)arguments[5]); } else if (methodName.equals("updateSettings")) { returnValue = updateSettings( diff --git a/portal-impl/src/com/liferay/portal/service/impl/LayoutSetPrototypeServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/LayoutSetPrototypeServiceImpl.java index 54d003e99c2b4b..c7824154f17135 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/LayoutSetPrototypeServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/LayoutSetPrototypeServiceImpl.java @@ -39,9 +39,8 @@ public class LayoutSetPrototypeServiceImpl extends LayoutSetPrototypeServiceBaseImpl { public LayoutSetPrototype addLayoutSetPrototype( - Map nameMap, String description, - boolean active, boolean layoutsUpdateable, - ServiceContext serviceContext) + Map nameMap, String description, boolean active, + boolean layoutsUpdateable, ServiceContext serviceContext) throws PortalException, SystemException { PortalPermissionUtil.check( @@ -50,8 +49,8 @@ public LayoutSetPrototype addLayoutSetPrototype( User user = getUser(); return layoutSetPrototypeLocalService.addLayoutSetPrototype( - user.getUserId(), user.getCompanyId(), nameMap, description, - active, layoutsUpdateable, serviceContext); + user.getUserId(), user.getCompanyId(), nameMap, description, active, + layoutsUpdateable, serviceContext); } public void deleteLayoutSetPrototype(long layoutSetPrototypeId) diff --git a/portal-impl/src/com/liferay/portal/service/impl/LayoutSetServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/LayoutSetServiceImpl.java index 9c65d2db4268c2..f171b33387d774 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/LayoutSetServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/LayoutSetServiceImpl.java @@ -66,8 +66,7 @@ public void updateLayoutSetPrototypeLinkEnabled( !layoutSetPrototypeLinkEnabled) { PortalPermissionUtil.check( - getPermissionChecker(), - ActionKeys.UNLINK_LAYOUT_SET_PROTOTYPE); + getPermissionChecker(), ActionKeys.UNLINK_LAYOUT_SET_PROTOTYPE); } layoutSetLocalService.updateLayoutSetPrototypeLinkEnabled( diff --git a/portal-impl/src/com/liferay/portal/service/impl/LayoutTemplateLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/LayoutTemplateLocalServiceImpl.java index 75c18e1aa253c4..cb51c1abf593e4 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/LayoutTemplateLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/LayoutTemplateLocalServiceImpl.java @@ -601,8 +601,8 @@ private Set> _readLayoutTemplates( if (customEl != null) { readLayoutTemplate( - servletContextName, servletContext, layoutTemplateIds, - customEl, false, null, pluginPackage); + servletContextName, servletContext, layoutTemplateIds, customEl, + false, null, pluginPackage); } return layoutTemplateIds; diff --git a/portal-impl/src/com/liferay/portal/service/impl/MembershipRequestLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/MembershipRequestLocalServiceImpl.java index 94ee922281bcb9..ca6769abf7ac09 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/MembershipRequestLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/MembershipRequestLocalServiceImpl.java @@ -202,8 +202,7 @@ public void updateStatus( notify( membershipRequest.getUserId(), membershipRequest, PropsKeys.SITES_EMAIL_MEMBERSHIP_REPLY_SUBJECT, - PropsKeys.SITES_EMAIL_MEMBERSHIP_REPLY_BODY, - serviceContext); + PropsKeys.SITES_EMAIL_MEMBERSHIP_REPLY_BODY, serviceContext); } } @@ -280,8 +279,8 @@ protected void notify( membershipRequest.getUserId()); String fromName = PrefsPropsUtil.getStringFromNames( - membershipRequest.getCompanyId(), - PropsKeys.SITES_EMAIL_FROM_NAME, PropsKeys.ADMIN_EMAIL_FROM_NAME); + membershipRequest.getCompanyId(), PropsKeys.SITES_EMAIL_FROM_NAME, + PropsKeys.ADMIN_EMAIL_FROM_NAME); String fromAddress = PrefsPropsUtil.getStringFromNames( membershipRequest.getCompanyId(), @@ -349,8 +348,7 @@ protected void notifyGroupAdministrators( notify( userId, membershipRequest, PropsKeys.SITES_EMAIL_MEMBERSHIP_REQUEST_SUBJECT, - PropsKeys.SITES_EMAIL_MEMBERSHIP_REQUEST_BODY, - serviceContext); + PropsKeys.SITES_EMAIL_MEMBERSHIP_REQUEST_BODY, serviceContext); } } diff --git a/portal-impl/src/com/liferay/portal/service/impl/OrganizationLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/OrganizationLocalServiceImpl.java index 79ff49b7997438..319023aeefda10 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/OrganizationLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/OrganizationLocalServiceImpl.java @@ -1040,8 +1040,7 @@ public Hits search( public List search( long companyId, long parentOrganizationId, String keywords, String type, Long regionId, Long countryId, - LinkedHashMap params, - int start, int end) + LinkedHashMap params, int start, int end) throws SystemException { return search( @@ -1093,8 +1092,8 @@ public List search( public List search( long companyId, long parentOrganizationId, String keywords, String type, Long regionId, Long countryId, - LinkedHashMap params, - int start, int end, OrderByComparator obc) + LinkedHashMap params, int start, int end, + OrderByComparator obc) throws SystemException { String parentOrganizationIdComparator = StringPool.EQUAL; @@ -1107,8 +1106,7 @@ public List search( return organizationFinder.findByKeywords( companyId, parentOrganizationId, parentOrganizationIdComparator, - keywords, type, regionId, countryId, params, start, end, - obc); + keywords, type, regionId, countryId, params, start, end, obc); } /** @@ -1157,8 +1155,8 @@ public List search( */ public List search( long companyId, long parentOrganizationId, String name, String type, - String street, String city, String zip, - Long regionId, Long countryId, + String street, String city, String zip, Long regionId, + Long countryId, LinkedHashMap params, boolean andOperator, int start, int end) throws SystemException { @@ -1218,8 +1216,8 @@ public List search( */ public List search( long companyId, long parentOrganizationId, String name, String type, - String street, String city, String zip, - Long regionId, Long countryId, LinkedHashMap params, + String street, String city, String zip, Long regionId, + Long countryId, LinkedHashMap params, boolean andOperator, int start, int end, OrderByComparator obc) throws SystemException { @@ -1414,8 +1412,8 @@ public int searchCount( */ public int searchCount( long companyId, long parentOrganizationId, String name, String type, - String street, String city, String zip, - Long regionId, Long countryId, LinkedHashMap params, + String street, String city, String zip, Long regionId, + Long countryId, LinkedHashMap params, boolean andOperator) throws SystemException { diff --git a/portal-impl/src/com/liferay/portal/service/impl/OrganizationServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/OrganizationServiceImpl.java index 44971e81fad183..58c3a58c1181bf 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/OrganizationServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/OrganizationServiceImpl.java @@ -606,9 +606,9 @@ public Organization updateOrganization( User user = getUser(); return organizationLocalService.updateOrganization( - user.getCompanyId(), organizationId, parentOrganizationId, - name, type, recursable, regionId, countryId, statusId, comments, - site, serviceContext); + user.getCompanyId(), organizationId, parentOrganizationId, name, + type, recursable, regionId, countryId, statusId, comments, site, + serviceContext); } } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portal/service/impl/PasswordPolicyLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/PasswordPolicyLocalServiceImpl.java index d6764be4069fc4..ec73d3b1e70b39 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/PasswordPolicyLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/PasswordPolicyLocalServiceImpl.java @@ -125,9 +125,9 @@ public void checkDefaultPasswordPolicy(long companyId) addPasswordPolicy( defaultUserId, true, defaultPasswordPolicyName, - defaultPasswordPolicyName, true, true, 0, false, true, 0, 6, - 0, 1, 0, 1, false, 6, false, 8640000, 86400, 0, false, 3, 0, - 600, 86400); + defaultPasswordPolicyName, true, true, 0, false, true, 0, 6, 0, + 1, 0, 1, false, 6, false, 8640000, 86400, 0, false, 3, 0, 600, + 86400); } } @@ -286,8 +286,8 @@ public PasswordPolicy updatePasswordPolicy( boolean checkSyntax, boolean allowDictionaryWords, int minAlphanumeric, int minLength, int minLowerCase, int minNumbers, int minSymbols, int minUpperCase, boolean history, - int historyCount, boolean expireable, long maxAge, - long warningTime, int graceLimit, boolean lockout, int maxFailure, + int historyCount, boolean expireable, long maxAge, long warningTime, + int graceLimit, boolean lockout, int maxFailure, long lockoutDuration, long resetFailureCount, long resetTicketMaxAge) throws PortalException, SystemException { diff --git a/portal-impl/src/com/liferay/portal/service/impl/PasswordPolicyServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/PasswordPolicyServiceImpl.java index ebb927edf1df7b..16905af2e29087 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/PasswordPolicyServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/PasswordPolicyServiceImpl.java @@ -65,8 +65,8 @@ public PasswordPolicy updatePasswordPolicy( boolean checkSyntax, boolean allowDictionaryWords, int minAlphanumeric, int minLength, int minLowerCase, int minNumbers, int minSymbols, int minUpperCase, boolean history, - int historyCount, boolean expireable, long maxAge, - long warningTime, int graceLimit, boolean lockout, int maxFailure, + int historyCount, boolean expireable, long maxAge, long warningTime, + int graceLimit, boolean lockout, int maxFailure, long lockoutDuration, long resetFailureCount, long resetTicketMaxAge) throws PortalException, SystemException { diff --git a/portal-impl/src/com/liferay/portal/service/impl/PermissionLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/PermissionLocalServiceImpl.java index 230e889f1dcf0c..87b6466efd696f 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/PermissionLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/PermissionLocalServiceImpl.java @@ -804,8 +804,8 @@ public void setGroupPermissions( * @throws SystemException if a system exception occurred */ public void setGroupPermissions( - String className, String classPK, long groupId, - String[] actionIds, long resourceId) + String className, String classPK, long groupId, String[] actionIds, + long resourceId) throws PortalException, SystemException { long associatedGroupId = 0; @@ -1481,8 +1481,7 @@ protected boolean hasUserPermissions_5( protected boolean hasUserPermissions_6( long userId, long resourceId, List resources, - String actionId, long[] roleIds, StopWatch stopWatch, - int block) + String actionId, long[] roleIds, StopWatch stopWatch, int block) throws PortalException, SystemException { boolean hasUserPermissions = diff --git a/portal-impl/src/com/liferay/portal/service/impl/PermissionServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/PermissionServiceImpl.java index e89d9444f5d259..7a056ea041f382 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/PermissionServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/PermissionServiceImpl.java @@ -243,8 +243,8 @@ public void setGroupPermissions( * @throws SystemException if a system exception occurred */ public void setGroupPermissions( - String className, String classPK, long groupId, - String[] actionIds, long resourceId) + String className, String classPK, long groupId, String[] actionIds, + long resourceId) throws PortalException, SystemException { checkPermission(getPermissionChecker(), groupId, resourceId); @@ -470,8 +470,7 @@ public void unsetUserPermissions( } protected void checkPermission( - PermissionChecker permissionChecker, long groupId, - long resourceId) + PermissionChecker permissionChecker, long groupId, long resourceId) throws PortalException, SystemException { Resource resource = resourcePersistence.findByPrimaryKey(resourceId); diff --git a/portal-impl/src/com/liferay/portal/service/impl/PortletServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/PortletServiceImpl.java index d1e34c664f558c..467aa0510326cb 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/PortletServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/PortletServiceImpl.java @@ -48,8 +48,7 @@ public JSONArray getWARPortlets() { jsonObject.put("portlet_name", portlet.getPortletName()); jsonObject.put( - "servlet_context_name", - portletApp.getServletContextName()); + "servlet_context_name", portletApp.getServletContextName()); jsonArray.put(jsonObject); } diff --git a/portal-impl/src/com/liferay/portal/service/impl/ResourceBlockLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/ResourceBlockLocalServiceImpl.java index de59d7c3f5b41c..940e76a425f06a 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/ResourceBlockLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/ResourceBlockLocalServiceImpl.java @@ -706,8 +706,8 @@ public void setIndividualScopePermissions( } public void updateCompanyScopePermissions( - long companyId, String name, long roleId, - long actionIdsLong, int operator) + long companyId, String name, long roleId, long actionIdsLong, + int operator) throws SystemException { resourceTypePermissionLocalService. diff --git a/portal-impl/src/com/liferay/portal/service/impl/ResourceLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/ResourceLocalServiceImpl.java index 8f926b1d48d90c..a3765896bc9aef 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/ResourceLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/ResourceLocalServiceImpl.java @@ -1,1285 +1,1285 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portal.service.impl; - -import com.liferay.portal.NoSuchResourceException; -import com.liferay.portal.ResourceActionsException; -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.search.SearchEngineUtil; -import com.liferay.portal.kernel.util.ListUtil; -import com.liferay.portal.model.AuditedModel; -import com.liferay.portal.model.ClassedModel; -import com.liferay.portal.model.Group; -import com.liferay.portal.model.GroupConstants; -import com.liferay.portal.model.GroupedModel; -import com.liferay.portal.model.Permission; -import com.liferay.portal.model.PermissionedModel; -import com.liferay.portal.model.Resource; -import com.liferay.portal.model.ResourceCode; -import com.liferay.portal.model.ResourceConstants; -import com.liferay.portal.model.ResourcePermission; -import com.liferay.portal.model.Role; -import com.liferay.portal.model.RoleConstants; -import com.liferay.portal.model.impl.ResourceImpl; -import com.liferay.portal.security.permission.PermissionCacheUtil; -import com.liferay.portal.security.permission.PermissionThreadLocal; -import com.liferay.portal.security.permission.PermissionsListFilter; -import com.liferay.portal.security.permission.PermissionsListFilterFactory; -import com.liferay.portal.security.permission.ResourceActionsUtil; -import com.liferay.portal.service.ServiceContext; -import com.liferay.portal.service.base.ResourceLocalServiceBaseImpl; -import com.liferay.portal.util.PropsValues; -import com.liferay.portal.util.ResourcePermissionsThreadLocal; -import com.liferay.portal.util.comparator.ResourceComparator; - -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; - -/** - * @author Brian Wing Shun Chan - * @author Wilson S. Man - * @author Raymond Augé - * @author Julio Camarero - * @author Connor McKay - */ -public class ResourceLocalServiceImpl extends ResourceLocalServiceBaseImpl { - - public void addModelResources( - AuditedModel auditedModel, ServiceContext serviceContext) - throws PortalException, SystemException { - - ClassedModel classedModel = (ClassedModel)auditedModel; - - if (serviceContext.isAddGroupPermissions() || - serviceContext.isAddGuestPermissions()) { - - addResources( - auditedModel.getCompanyId(), getGroupId(auditedModel), - auditedModel.getUserId(), classedModel.getModelClassName(), - String.valueOf(classedModel.getPrimaryKeyObj()), false, - serviceContext.isAddGroupPermissions(), - serviceContext.isAddGuestPermissions(), - getPermissionedModel(auditedModel)); - } - else { - if (serviceContext.isDeriveDefaultPermissions()) { - serviceContext.deriveDefaultPermissions( - getGroupId(auditedModel), classedModel.getModelClassName()); - } - - addModelResources( - auditedModel.getCompanyId(), getGroupId(auditedModel), - auditedModel.getUserId(), classedModel.getModelClassName(), - String.valueOf(classedModel.getPrimaryKeyObj()), - serviceContext.getGroupPermissions(), - serviceContext.getGuestPermissions(), - getPermissionedModel(auditedModel)); - } - } - - public void addModelResources( - long companyId, long groupId, long userId, String name, - long primKey, String[] groupPermissions, String[] guestPermissions) - throws PortalException, SystemException { - - addModelResources( - companyId, groupId, userId, name, String.valueOf(primKey), - groupPermissions, guestPermissions, null); - } - - public void addModelResources( - long companyId, long groupId, long userId, String name, - String primKey, String[] groupPermissions, - String[] guestPermissions) - throws PortalException, SystemException { - - addModelResources( - companyId, groupId, userId, name, primKey, groupPermissions, - guestPermissions, null); - } - - public Resource addResource( - long companyId, String name, int scope, String primKey) - throws SystemException { - - if (!PermissionThreadLocal.isAddResource()) { - return null; - } - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - return addResource_6(companyId, name, scope, primKey); - } - else { - return addResource_1to5(companyId, name, scope, primKey); - } - } - - public void addResources( - long companyId, long groupId, long userId, String name, - long primKey, boolean portletActions, - boolean addGroupPermissions, boolean addGuestPermissions) - throws PortalException, SystemException { - - addResources( - companyId, groupId, userId, name, String.valueOf(primKey), - portletActions, addGroupPermissions, addGuestPermissions, null); - } - - public void addResources( - long companyId, long groupId, long userId, String name, - String primKey, boolean portletActions, - boolean addGroupPermissions, boolean addGuestPermissions) - throws PortalException, SystemException { - - addResources( - companyId, groupId, userId, name, primKey, portletActions, - addGroupPermissions, addGuestPermissions, null); - } - - public void addResources( - long companyId, long groupId, String name, boolean portletActions) - throws PortalException, SystemException { - - addResources( - companyId, groupId, 0, name, null, portletActions, false, false); - } - - public void deleteResource(AuditedModel auditedModel, int scope) - throws PortalException, SystemException { - - ClassedModel classedModel = (ClassedModel)auditedModel; - - deleteResource( - auditedModel.getCompanyId(), classedModel.getModelClassName(), - scope, String.valueOf(classedModel.getPrimaryKeyObj()), - getPermissionedModel(auditedModel)); - } - - @Override - public void deleteResource(long resourceId) throws SystemException { - try { - Resource resource = resourcePersistence.findByPrimaryKey( - resourceId); - - deleteResource(resource); - } - catch (NoSuchResourceException nsre) { - if (_log.isWarnEnabled()) { - _log.warn(nsre); - } - } - } - - public void deleteResource( - long companyId, String name, int scope, long primKey) - throws PortalException, SystemException { - - deleteResource(companyId, name, scope, String.valueOf(primKey), null); - } - - public void deleteResource( - long companyId, String name, int scope, String primKey) - throws PortalException, SystemException { - - deleteResource(companyId, name, scope, primKey, null); - } - - @Override - public void deleteResource(Resource resource) throws SystemException { - - // Permissions - - List permissions = permissionPersistence.findByResourceId( - resource.getResourceId()); - - for (Permission permission : permissions) { - orgGroupPermissionPersistence.removeByPermissionId( - permission.getPermissionId()); - } - - permissionPersistence.removeByResourceId(resource.getResourceId()); - - // Resource - - resourcePersistence.remove(resource); - } - - public void deleteResources(String name) throws SystemException { - List resources = resourceFinder.findByName(name); - - for (Resource resource : resources) { - deleteResource(resource); - } - } - - public Resource fetchResource( - long companyId, String name, int scope, String primKey) - throws SystemException { - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - return getResource_6(companyId, name, scope, primKey); - } - else { - return fetchResource_1to5(companyId, name, scope, primKey); - } - } - - public long getLatestResourceId() throws SystemException { - List resources = resourcePersistence.findAll( - 0, 1, new ResourceComparator()); - - if (resources.size() == 0) { - return 0; - } - else { - Resource resource = resources.get(0); - - return resource.getResourceId(); - } - } - - @Override - public Resource getResource(long resourceId) - throws PortalException, SystemException { - - return resourcePersistence.findByPrimaryKey(resourceId); - } - - public Resource getResource( - long companyId, String name, int scope, String primKey) - throws PortalException, SystemException { - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - return getResource_6(companyId, name, scope, primKey); - } - else { - return getResource_1to5(companyId, name, scope, primKey); - } - } - - public List getResources() throws SystemException { - return resourcePersistence.findAll(); - } - - public void updateModelResources( - AuditedModel auditedModel, ServiceContext serviceContext) - throws PortalException, SystemException { - - ClassedModel classedModel = (ClassedModel)auditedModel; - - updateResources( - auditedModel.getCompanyId(), getGroupId(auditedModel), - classedModel.getModelClassName(), - String.valueOf(classedModel.getPrimaryKeyObj()), - serviceContext.getGroupPermissions(), - serviceContext.getGuestPermissions(), - getPermissionedModel(auditedModel)); - } - - public void updateResources( - long companyId, long groupId, String name, long primKey, - String[] groupPermissions, String[] guestPermissions) - throws PortalException, SystemException { - - updateResources( - companyId, groupId, name, String.valueOf(primKey), groupPermissions, - guestPermissions, null); - } - - public void updateResources( - long companyId, long groupId, String name, String primKey, - String[] groupPermissions, String[] guestPermissions) - throws PortalException, SystemException { - - updateResources( - companyId, groupId, name, primKey, groupPermissions, - guestPermissions, null); - } - - public void updateResources( - long companyId, String name, int scope, String primKey, - String newPrimKey) - throws PortalException, SystemException { - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - if (resourceBlockLocalService.isSupported(name)) { - - // Assuming that this method is used when the primary key of an - // existing record is changed, then nothing needs to happen - // here, as it should still have its resource block ID. - - } - else { - updateResources_6(companyId, name, scope, primKey, newPrimKey); - } - } - else { - updateResources_1to5(companyId, name, scope, primKey, newPrimKey); - } - } - - protected void addGroupPermissions( - long companyId, long groupId, long userId, String name, - Resource resource, boolean portletActions, - PermissionedModel permissionedModel) - throws PortalException, SystemException { - - List actions = null; - - if (portletActions) { - actions = ResourceActionsUtil.getPortletResourceGroupDefaultActions( - name); - } - else { - actions = ResourceActionsUtil.getModelResourceGroupDefaultActions( - name); - } - - String[] actionIds = actions.toArray(new String[actions.size()]); - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - if (resourceBlockLocalService.isSupported(name)) { - addGroupPermissions_6Blocks( - groupId, resource, actions, permissionedModel); - } - else { - addGroupPermissions_6(groupId, resource, actionIds); - } - } - else { - addGroupPermissions_1to5( - companyId, groupId, userId, name, resource, portletActions, - actionIds); - } - } - - protected void addGroupPermissions_1to5( - long companyId, long groupId, long userId, String name, - Resource resource, boolean portletActions, String[] actionIds) - throws PortalException, SystemException { - - long resourceId = resource.getResourceId(); - String primKey = resource.getPrimKey(); - - List groupPermissionsList = - permissionLocalService.getPermissions( - companyId, actionIds, resourceId); - - PermissionsListFilter permissionsListFilter = - PermissionsListFilterFactory.getInstance(); - - groupPermissionsList = permissionsListFilter.filterGroupPermissions( - companyId, groupId, userId, name, primKey, portletActions, - groupPermissionsList); - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { - Role role = roleLocalService.getDefaultGroupRole(groupId); - - rolePersistence.addPermissions( - role.getRoleId(), groupPermissionsList); - } - else { - groupPersistence.addPermissions(groupId, groupPermissionsList); - } - } - - protected void addGroupPermissions_6( - long groupId, Resource resource, String[] actionIds) - throws PortalException, SystemException { - - Role role = roleLocalService.getDefaultGroupRole(groupId); - - resourcePermissionLocalService.setResourcePermissions( - resource.getCompanyId(), resource.getName(), resource.getScope(), - resource.getPrimKey(), role.getRoleId(), actionIds); - } - - protected void addGroupPermissions_6Blocks( - long groupId, Resource resource, List actionIds, - PermissionedModel permissionedModel) - throws PortalException, SystemException { - - if (permissionedModel == null) { - throw new IllegalArgumentException("Permissioned model is null"); - } - - // Scope is assumed to always be individual - - Role role = roleLocalService.getDefaultGroupRole(groupId); - - resourceBlockLocalService.setIndividualScopePermissions( - resource.getCompanyId(), groupId, resource.getName(), - permissionedModel, role.getRoleId(), actionIds); - } - - protected void addGuestPermissions( - long companyId, long groupId, long userId, String name, - Resource resource, boolean portletActions, - PermissionedModel permissionedModel) - throws PortalException, SystemException { - - List actions = null; - - if (portletActions) { - actions = ResourceActionsUtil.getPortletResourceGuestDefaultActions( - name); - } - else { - actions = ResourceActionsUtil.getModelResourceGuestDefaultActions( - name); - } - - String[] actionIds = actions.toArray(new String[actions.size()]); - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - if (resourceBlockLocalService.isSupported(name)) { - addGuestPermissions_6Blocks( - companyId, groupId, resource, actions, permissionedModel); - } - else { - addGuestPermissions_6(companyId, resource, actionIds); - } - } - else { - addGuestPermissions_1to5( - companyId, groupId, userId, name, resource, portletActions, - actionIds); - } - } - - protected void addGuestPermissions_1to5( - long companyId, long groupId, long userId, String name, - Resource resource, boolean portletActions, String[] actionIds) - throws PortalException, SystemException { - - List guestPermissionsList = - permissionLocalService.getPermissions( - companyId, actionIds, resource.getResourceId()); - - PermissionsListFilter permissionsListFilter = - PermissionsListFilterFactory.getInstance(); - - guestPermissionsList = permissionsListFilter.filterGuestPermissions( - companyId, groupId, userId, name, resource.getPrimKey(), - portletActions, guestPermissionsList); - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { - Role guestRole = roleLocalService.getRole( - companyId, RoleConstants.GUEST); - - rolePersistence.addPermissions( - guestRole.getRoleId(), guestPermissionsList); - } - else { - long defaultUserId = userLocalService.getDefaultUserId(companyId); - - userPersistence.addPermissions(defaultUserId, guestPermissionsList); - } - } - - protected void addGuestPermissions_6( - long companyId, Resource resource, String[] actionIds) - throws PortalException, SystemException { - - Role guestRole = roleLocalService.getRole( - companyId, RoleConstants.GUEST); - - resourcePermissionLocalService.setResourcePermissions( - resource.getCompanyId(), resource.getName(), resource.getScope(), - resource.getPrimKey(), guestRole.getRoleId(), actionIds); - } - - protected void addGuestPermissions_6Blocks( - long companyId, long groupId, Resource resource, - List actionIds, PermissionedModel permissionedModel) - throws PortalException, SystemException { - - if (permissionedModel == null) { - throw new IllegalArgumentException("Permissioned model is null"); - } - - // Scope is assumed to always be individual - - Role guestRole = roleLocalService.getRole( - companyId, RoleConstants.GUEST); - - resourceBlockLocalService.setIndividualScopePermissions( - resource.getCompanyId(), groupId, resource.getName(), - permissionedModel, guestRole.getRoleId(), actionIds); - } - - protected void addModelResources( - long companyId, long groupId, long userId, String name, - String primKey, String[] groupPermissions, - String[] guestPermissions, PermissionedModel permissionedModel) - throws PortalException, SystemException { - - if (!PermissionThreadLocal.isAddResource()) { - return; - } - - validate(name, false); - - // Company - - addResource( - companyId, name, ResourceConstants.SCOPE_COMPANY, - String.valueOf(companyId)); - - // Guest - - Group guestGroup = groupLocalService.getGroup( - companyId, GroupConstants.GUEST); - - addResource( - companyId, name, ResourceConstants.SCOPE_GROUP, - String.valueOf(guestGroup.getGroupId())); - - // Group - - if ((groupId > 0) && (guestGroup.getGroupId() != groupId)) { - addResource( - companyId, name, ResourceConstants.SCOPE_GROUP, - String.valueOf(groupId)); - } - - if (primKey == null) { - return; - } - - // Individual - - Resource resource = addResource( - companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey); - - // Permissions - - boolean flushEnabled = PermissionThreadLocal.isFlushEnabled(); - - PermissionThreadLocal.setIndexEnabled(false); - - try { - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - addModelResources_6( - companyId, groupId, userId, resource, groupPermissions, - guestPermissions, permissionedModel); - } - else { - addModelResources_1to5( - companyId, groupId, userId, resource, groupPermissions, - guestPermissions); - } - } - finally { - PermissionThreadLocal.setIndexEnabled(flushEnabled); - - PermissionCacheUtil.clearCache(); - - SearchEngineUtil.updatePermissionFields(name, primKey); - } - } - - protected void addModelResources_1to5( - long companyId, long groupId, long userId, Resource resource, - String[] groupPermissions, String[] guestPermissions) - throws PortalException, SystemException { - - long defaultUserId = userLocalService.getDefaultUserId(companyId); - - PermissionsListFilter permissionsListFilter = - PermissionsListFilterFactory.getInstance(); - - List permissionsList = - permissionLocalService.addPermissions( - companyId, resource.getName(), resource.getResourceId(), false); - - List userPermissionsList = - permissionsListFilter.filterUserPermissions( - companyId, groupId, userId, resource.getName(), - resource.getPrimKey(), false, permissionsList); - - filterOwnerPermissions(resource.getName(), userPermissionsList); - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { - - // Owner permissions - - Role ownerRole = roleLocalService.getRole( - companyId, RoleConstants.OWNER); - - rolePersistence.addPermissions( - ownerRole.getRoleId(), userPermissionsList); - } - else { - - // User permissions - - if ((userId > 0) && (userId != defaultUserId)) { - userPersistence.addPermissions(userId, userPermissionsList); - } - } - - // Group permissions - - if (groupId > 0) { - if (groupPermissions == null) { - groupPermissions = new String[0]; - } - - List groupPermissionsList = - permissionLocalService.getPermissions( - companyId, groupPermissions, resource.getResourceId()); - - groupPermissionsList = permissionsListFilter.filterGroupPermissions( - companyId, groupId, userId, resource.getName(), - resource.getPrimKey(), false, groupPermissionsList); - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { - Role role = roleLocalService.getDefaultGroupRole(groupId); - - rolePersistence.addPermissions( - role.getRoleId(), groupPermissionsList); - } - else { - groupPersistence.addPermissions(groupId, groupPermissionsList); - } - } - - // Guest permissions - - if (guestPermissions == null) { - guestPermissions = new String[0]; - } - - List guestPermissionsList = - permissionLocalService.getPermissions( - companyId, guestPermissions, resource.getResourceId()); - - guestPermissionsList = permissionsListFilter.filterGuestPermissions( - companyId, groupId, userId, resource.getName(), - resource.getPrimKey(), false, guestPermissionsList); - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { - Role guestRole = roleLocalService.getRole( - companyId, RoleConstants.GUEST); - - rolePersistence.addPermissions( - guestRole.getRoleId(), guestPermissionsList); - } - else { - userPersistence.addPermissions(defaultUserId, guestPermissionsList); - } - } - - protected void addModelResources_6( - long companyId, long groupId, long userId, Resource resource, - String[] groupPermissions, String[] guestPermissions, - PermissionedModel permissionedModel) - throws PortalException, SystemException { - - // Owner permissions - - Role ownerRole = roleLocalService.getRole( - companyId, RoleConstants.OWNER); - - List ownerActionIds = - ResourceActionsUtil.getModelResourceActions(resource.getName()); - - ownerActionIds = ListUtil.copy(ownerActionIds); - - filterOwnerActions(resource.getName(), ownerActionIds); - - String[] ownerPermissions = ownerActionIds.toArray( - new String[ownerActionIds.size()]); - - // Group permissions - - Role defaultGroupRole = null; - - if (groupId > 0) { - defaultGroupRole = roleLocalService.getDefaultGroupRole(groupId); - - if (groupPermissions == null) { - groupPermissions = new String[0]; - } - } - - // Guest permissions - - Role guestRole = roleLocalService.getRole( - companyId, RoleConstants.GUEST); - - if (guestPermissions == null) { - guestPermissions = new String[0]; - } - - if (resourceBlockLocalService.isSupported(resource.getName())) { - - if (permissionedModel == null) { - throw new IllegalArgumentException( - "Permissioned model is null"); - } - - // Scope is assumed to always be individual - - resourceBlockLocalService.setIndividualScopePermissions( - resource.getCompanyId(), groupId, resource.getName(), - permissionedModel, ownerRole.getRoleId(), ownerActionIds); - - if (groupId > 0) { - resourceBlockLocalService.setIndividualScopePermissions( - resource.getCompanyId(), groupId, resource.getName(), - permissionedModel, defaultGroupRole.getRoleId(), - Arrays.asList(groupPermissions)); - } - - resourceBlockLocalService.setIndividualScopePermissions( - resource.getCompanyId(), groupId, resource.getName(), - permissionedModel, guestRole.getRoleId(), - Arrays.asList(guestPermissions)); - } - else { - resourcePermissionLocalService.setOwnerResourcePermissions( - resource.getCompanyId(), resource.getName(), - resource.getScope(), resource.getPrimKey(), - ownerRole.getRoleId(), userId, ownerPermissions); - - if (groupId > 0) { - resourcePermissionLocalService.setResourcePermissions( - resource.getCompanyId(), resource.getName(), - resource.getScope(), resource.getPrimKey(), - defaultGroupRole.getRoleId(), groupPermissions); - } - - resourcePermissionLocalService.setResourcePermissions( - resource.getCompanyId(), resource.getName(), - resource.getScope(), resource.getPrimKey(), - guestRole.getRoleId(), guestPermissions); - } - } - - protected Resource addResource_1to5( - long companyId, String name, int scope, String primKey) - throws SystemException { - - ResourceCode resourceCode = resourceCodeLocalService.getResourceCode( - companyId, name, scope); - - long codeId = resourceCode.getCodeId(); - - Resource resource = resourcePersistence.fetchByC_P(codeId, primKey); - - if (resource == null) { - long resourceId = counterLocalService.increment( - Resource.class.getName()); - - resource = resourcePersistence.create(resourceId); - - resource.setCodeId(codeId); - resource.setPrimKey(primKey); - - try { - resourcePersistence.update(resource, false); - } - catch (SystemException se) { - if (_log.isWarnEnabled()) { - _log.warn( - "Add failed, fetch {codeId=" + codeId + ", primKey=" + - primKey + "}"); - } - - resource = resourcePersistence.fetchByC_P( - codeId, primKey, false); - - if (resource == null) { - throw se; - } - } - } - - return resource; - } - - protected Resource addResource_6( - long companyId, String name, int scope, String primKey) { - - Resource resource = new ResourceImpl(); - - resource.setCompanyId(companyId); - resource.setName(name); - resource.setScope(scope); - resource.setPrimKey(primKey); - - return resource; - } - - protected void addResources( - long companyId, long groupId, long userId, String name, - String primKey, boolean portletActions, boolean addGroupPermissions, - boolean addGuestPermissions, PermissionedModel permissionedModel) - throws PortalException, SystemException { - - if (!PermissionThreadLocal.isAddResource()) { - return; - } - - validate(name, portletActions); - - // Company - - addResource( - companyId, name, ResourceConstants.SCOPE_COMPANY, - String.valueOf(companyId)); - - if (groupId > 0) { - addResource( - companyId, name, ResourceConstants.SCOPE_GROUP, - String.valueOf(groupId)); - } - - if (primKey == null) { - return; - } - - // Individual - - Resource resource = addResource( - companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey); - - // Permissions - - boolean flushEnabled = PermissionThreadLocal.isFlushEnabled(); - - PermissionThreadLocal.setIndexEnabled(false); - - List resourcePermissions = - resourcePermissionPersistence.findByC_N_S_P( - companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey); - - ResourcePermissionsThreadLocal.setResourcePermissions( - resourcePermissions); - - try { - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - addResources_6( - companyId, groupId, userId, resource, portletActions, - permissionedModel); - } - else { - addResources_1to5( - companyId, groupId, userId, resource, portletActions); - } - - // Group permissions - - if ((groupId > 0) && addGroupPermissions) { - addGroupPermissions( - companyId, groupId, userId, name, resource, portletActions, - permissionedModel); - } - - // Guest permissions - - if (addGuestPermissions) { - - // Don't add guest permissions when you've already added group - // permissions and the given group is the guest group. - - addGuestPermissions( - companyId, groupId, userId, name, resource, portletActions, - permissionedModel); - } - } - finally { - ResourcePermissionsThreadLocal.setResourcePermissions(null); - - PermissionThreadLocal.setIndexEnabled(flushEnabled); - - PermissionCacheUtil.clearCache(); - - SearchEngineUtil.updatePermissionFields(name, primKey); - } - } - - protected void addResources_1to5( - long companyId, long groupId, long userId, Resource resource, - boolean portletActions) - throws PortalException, SystemException { - - List permissionsList = - permissionLocalService.addPermissions( - companyId, resource.getName(), resource.getResourceId(), - portletActions); - - PermissionsListFilter permissionsListFilter = - PermissionsListFilterFactory.getInstance(); - - List userPermissionsList = - permissionsListFilter.filterUserPermissions( - companyId, groupId, userId, resource.getName(), - resource.getPrimKey(), portletActions, permissionsList); - - filterOwnerPermissions(resource.getName(), userPermissionsList); - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { - - // Owner permissions - - Role ownerRole = roleLocalService.getRole( - companyId, RoleConstants.OWNER); - - rolePersistence.addPermissions( - ownerRole.getRoleId(), userPermissionsList); - } - else { - - // User permissions - - long defaultUserId = userLocalService.getDefaultUserId(companyId); - - if ((userId > 0) && (userId != defaultUserId)) { - userPersistence.addPermissions(userId, userPermissionsList); - } - } - } - - protected void addResources_6( - long companyId, long groupId, long userId, Resource resource, - boolean portletActions, PermissionedModel permissionedModel) - throws PortalException, SystemException { - - List actionIds = null; - - if (portletActions) { - actionIds = ResourceActionsUtil.getPortletResourceActions( - resource.getName()); - } - else { - actionIds = ResourceActionsUtil.getModelResourceActions( - resource.getName()); - - actionIds = ListUtil.copy(actionIds); - - filterOwnerActions(resource.getName(), actionIds); - } - - Role role = roleLocalService.getRole(companyId, RoleConstants.OWNER); - - if (resourceBlockLocalService.isSupported(resource.getName())) { - if (permissionedModel == null) { - throw new IllegalArgumentException( - "Permissioned model is null"); - } - - // Scope is assumed to always be individual - - resourceBlockLocalService.setIndividualScopePermissions( - resource.getCompanyId(), groupId, resource.getName(), - permissionedModel, role.getRoleId(), actionIds); - } - else { - resourcePermissionLocalService.setOwnerResourcePermissions( - resource.getCompanyId(), resource.getName(), - resource.getScope(), resource.getPrimKey(), role.getRoleId(), - userId, actionIds.toArray(new String[actionIds.size()])); - } - } - - protected void deleteResource( - long companyId, String name, int scope, String primKey, - PermissionedModel permissionedModel) - throws PortalException, SystemException{ - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - if (resourceBlockLocalService.isSupported(name)) { - if (permissionedModel == null) { - throw new IllegalArgumentException( - "Permissioned model is null"); - } - - resourceBlockLocalService.releasePermissionedModelResourceBlock( - permissionedModel); - - return; - } - else { - resourcePermissionLocalService.deleteResourcePermissions( - companyId, name, scope, primKey); - - return; - } - } - - try { - Resource resource = getResource(companyId, name, scope, primKey); - - deleteResource(resource.getResourceId()); - } - catch (NoSuchResourceException nsre) { - if (_log.isWarnEnabled()) { - _log.warn(nsre); - } - } - } - - protected Resource fetchResource_1to5( - long companyId, String name, int scope, String primKey) - throws SystemException { - - ResourceCode resourceCode = resourceCodeLocalService.getResourceCode( - companyId, name, scope); - - return resourcePersistence.fetchByC_P( - resourceCode.getCodeId(), primKey); - } - - protected void filterOwnerActions(String name, List actionIds) { - List defaultOwnerActions = - ResourceActionsUtil.getModelResourceOwnerDefaultActions(name); - - if (defaultOwnerActions.isEmpty()) { - return; - } - - Iterator itr = actionIds.iterator(); - - while (itr.hasNext()) { - String actionId = itr.next(); - - if (!defaultOwnerActions.contains(actionId)) { - itr.remove(); - } - } - } - - protected void filterOwnerPermissions( - String name, List permissions) { - - List defaultOwnerActions = - ResourceActionsUtil.getModelResourceOwnerDefaultActions(name); - - if (defaultOwnerActions.isEmpty()) { - return; - } - - Iterator itr = permissions.iterator(); - - while (itr.hasNext()) { - Permission permission = itr.next(); - - String actionId = permission.getActionId(); - - if (!defaultOwnerActions.contains(actionId)) { - itr.remove(); - } - } - } - - protected long getGroupId(AuditedModel auditedModel) { - long groupId = 0; - - if (auditedModel instanceof GroupedModel) { - GroupedModel groupedModel = (GroupedModel)auditedModel; - - groupId = groupedModel.getGroupId(); - } - - return groupId; - } - - protected PermissionedModel getPermissionedModel( - AuditedModel auditedModel) { - - PermissionedModel permissionedModel = null; - - if (auditedModel instanceof PermissionedModel) { - permissionedModel = (PermissionedModel)auditedModel; - } - - return permissionedModel; - } - - protected Resource getResource_1to5( - long companyId, String name, int scope, String primKey) - throws PortalException, SystemException { - - ResourceCode resourceCode = resourceCodeLocalService.getResourceCode( - companyId, name, scope); - - return resourcePersistence.findByC_P(resourceCode.getCodeId(), primKey); - } - - protected Resource getResource_6( - long companyId, String name, int scope, String primKey) { - - Resource resource = new ResourceImpl(); - - resource.setCompanyId(companyId); - resource.setName(name); - resource.setScope(scope); - resource.setPrimKey(primKey); - - return resource; - } - - protected void updateResources( - long companyId, long groupId, String name, String primKey, - String[] groupPermissions, String[] guestPermissions, - PermissionedModel permissionedModel) - throws PortalException, SystemException { - - Resource resource = getResource( - companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey); - - if (groupPermissions == null) { - groupPermissions = new String[0]; - } - - if (guestPermissions == null) { - guestPermissions = new String[0]; - } - - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - if (resourceBlockLocalService.isSupported(name)) { - updateResources_6Blocks( - companyId, groupId, resource, groupPermissions, - guestPermissions, permissionedModel); - } - else { - updateResources_6( - companyId, groupId, resource, groupPermissions, - guestPermissions); - } - } - else { - updateResources_1to5( - companyId, groupId, resource, groupPermissions, - guestPermissions); - } - } - - protected void updateResources_1to5( - long companyId, long groupId, Resource resource, - String[] groupPermissions, String[] guestPermissions) - throws PortalException, SystemException { - - Role role = roleLocalService.getDefaultGroupRole(groupId); - - permissionLocalService.setRolePermissions( - role.getRoleId(), groupPermissions, resource.getResourceId()); - - role = roleLocalService.getRole(companyId, RoleConstants.GUEST); - - permissionLocalService.setRolePermissions( - role.getRoleId(), guestPermissions, resource.getResourceId()); - } - - protected void updateResources_1to5( - long companyId, String name, int scope, String primKey, - String newPrimKey) - throws PortalException, SystemException { - - Resource resource = getResource(companyId, name, scope, primKey); - - resource.setPrimKey(newPrimKey); - - resourcePersistence.update(resource, false); - } - - protected void updateResources_6( - long companyId, long groupId, Resource resource, - String[] groupPermissions, String[] guestPermissions) - throws PortalException, SystemException { - - Role role = roleLocalService.getDefaultGroupRole(groupId); - - resourcePermissionLocalService.setResourcePermissions( - resource.getCompanyId(), resource.getName(), resource.getScope(), - resource.getPrimKey(), role.getRoleId(), groupPermissions); - - role = roleLocalService.getRole(companyId, RoleConstants.GUEST); - - resourcePermissionLocalService.setResourcePermissions( - resource.getCompanyId(), resource.getName(), resource.getScope(), - resource.getPrimKey(), role.getRoleId(), guestPermissions); - } - - protected void updateResources_6( - long companyId, String name, int scope, String primKey, - String newPrimKey) - throws SystemException { - - List resourcePermissions = - resourcePermissionLocalService.getResourcePermissions( - companyId, name, scope, primKey); - - for (ResourcePermission resourcePermission : resourcePermissions) { - resourcePermission.setPrimKey(newPrimKey); - - resourcePermissionPersistence.update(resourcePermission, false); - } - } - - protected void updateResources_6Blocks( - long companyId, long groupId, Resource resource, - String[] groupPermissions, String[] guestPermissions, - PermissionedModel permissionedModel) - throws PortalException, SystemException { - - if (permissionedModel == null) { - throw new IllegalArgumentException("Permissioned model is null"); - } - - // Scope is assumed to always be individual - - Role role = roleLocalService.getDefaultGroupRole(groupId); - - resourceBlockLocalService.setIndividualScopePermissions( - companyId, groupId, resource.getName(), permissionedModel, - role.getRoleId(), Arrays.asList(groupPermissions)); - - role = roleLocalService.getRole(companyId, RoleConstants.GUEST); - - resourceBlockLocalService.setIndividualScopePermissions( - companyId, groupId, resource.getName(), permissionedModel, - role.getRoleId(), Arrays.asList(guestPermissions)); - } - - protected void validate(String name, boolean portletActions) - throws PortalException { - - List actions = null; - - if (portletActions) { - actions = ResourceActionsUtil.getPortletResourceActions(name); - } - else { - actions = ResourceActionsUtil.getModelResourceActions(name); - } - - if (actions.size() == 0) { - throw new ResourceActionsException( - "There are no actions associated with the resource " + name); - } - } - - private static Log _log = LogFactoryUtil.getLog( - ResourceLocalServiceImpl.class); - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portal.service.impl; + +import com.liferay.portal.NoSuchResourceException; +import com.liferay.portal.ResourceActionsException; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.search.SearchEngineUtil; +import com.liferay.portal.kernel.util.ListUtil; +import com.liferay.portal.model.AuditedModel; +import com.liferay.portal.model.ClassedModel; +import com.liferay.portal.model.Group; +import com.liferay.portal.model.GroupConstants; +import com.liferay.portal.model.GroupedModel; +import com.liferay.portal.model.Permission; +import com.liferay.portal.model.PermissionedModel; +import com.liferay.portal.model.Resource; +import com.liferay.portal.model.ResourceCode; +import com.liferay.portal.model.ResourceConstants; +import com.liferay.portal.model.ResourcePermission; +import com.liferay.portal.model.Role; +import com.liferay.portal.model.RoleConstants; +import com.liferay.portal.model.impl.ResourceImpl; +import com.liferay.portal.security.permission.PermissionCacheUtil; +import com.liferay.portal.security.permission.PermissionThreadLocal; +import com.liferay.portal.security.permission.PermissionsListFilter; +import com.liferay.portal.security.permission.PermissionsListFilterFactory; +import com.liferay.portal.security.permission.ResourceActionsUtil; +import com.liferay.portal.service.ServiceContext; +import com.liferay.portal.service.base.ResourceLocalServiceBaseImpl; +import com.liferay.portal.util.PropsValues; +import com.liferay.portal.util.ResourcePermissionsThreadLocal; +import com.liferay.portal.util.comparator.ResourceComparator; + +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; + +/** + * @author Brian Wing Shun Chan + * @author Wilson S. Man + * @author Raymond Augé + * @author Julio Camarero + * @author Connor McKay + */ +public class ResourceLocalServiceImpl extends ResourceLocalServiceBaseImpl { + + public void addModelResources( + AuditedModel auditedModel, ServiceContext serviceContext) + throws PortalException, SystemException { + + ClassedModel classedModel = (ClassedModel)auditedModel; + + if (serviceContext.isAddGroupPermissions() || + serviceContext.isAddGuestPermissions()) { + + addResources( + auditedModel.getCompanyId(), getGroupId(auditedModel), + auditedModel.getUserId(), classedModel.getModelClassName(), + String.valueOf(classedModel.getPrimaryKeyObj()), false, + serviceContext.isAddGroupPermissions(), + serviceContext.isAddGuestPermissions(), + getPermissionedModel(auditedModel)); + } + else { + if (serviceContext.isDeriveDefaultPermissions()) { + serviceContext.deriveDefaultPermissions( + getGroupId(auditedModel), classedModel.getModelClassName()); + } + + addModelResources( + auditedModel.getCompanyId(), getGroupId(auditedModel), + auditedModel.getUserId(), classedModel.getModelClassName(), + String.valueOf(classedModel.getPrimaryKeyObj()), + serviceContext.getGroupPermissions(), + serviceContext.getGuestPermissions(), + getPermissionedModel(auditedModel)); + } + } + + public void addModelResources( + long companyId, long groupId, long userId, String name, + long primKey, String[] groupPermissions, String[] guestPermissions) + throws PortalException, SystemException { + + addModelResources( + companyId, groupId, userId, name, String.valueOf(primKey), + groupPermissions, guestPermissions, null); + } + + public void addModelResources( + long companyId, long groupId, long userId, String name, + String primKey, String[] groupPermissions, + String[] guestPermissions) + throws PortalException, SystemException { + + addModelResources( + companyId, groupId, userId, name, primKey, groupPermissions, + guestPermissions, null); + } + + public Resource addResource( + long companyId, String name, int scope, String primKey) + throws SystemException { + + if (!PermissionThreadLocal.isAddResource()) { + return null; + } + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + return addResource_6(companyId, name, scope, primKey); + } + else { + return addResource_1to5(companyId, name, scope, primKey); + } + } + + public void addResources( + long companyId, long groupId, long userId, String name, + long primKey, boolean portletActions, boolean addGroupPermissions, + boolean addGuestPermissions) + throws PortalException, SystemException { + + addResources( + companyId, groupId, userId, name, String.valueOf(primKey), + portletActions, addGroupPermissions, addGuestPermissions, null); + } + + public void addResources( + long companyId, long groupId, long userId, String name, + String primKey, boolean portletActions, boolean addGroupPermissions, + boolean addGuestPermissions) + throws PortalException, SystemException { + + addResources( + companyId, groupId, userId, name, primKey, portletActions, + addGroupPermissions, addGuestPermissions, null); + } + + public void addResources( + long companyId, long groupId, String name, boolean portletActions) + throws PortalException, SystemException { + + addResources( + companyId, groupId, 0, name, null, portletActions, false, false); + } + + public void deleteResource(AuditedModel auditedModel, int scope) + throws PortalException, SystemException { + + ClassedModel classedModel = (ClassedModel)auditedModel; + + deleteResource( + auditedModel.getCompanyId(), classedModel.getModelClassName(), + scope, String.valueOf(classedModel.getPrimaryKeyObj()), + getPermissionedModel(auditedModel)); + } + + @Override + public void deleteResource(long resourceId) throws SystemException { + try { + Resource resource = resourcePersistence.findByPrimaryKey( + resourceId); + + deleteResource(resource); + } + catch (NoSuchResourceException nsre) { + if (_log.isWarnEnabled()) { + _log.warn(nsre); + } + } + } + + public void deleteResource( + long companyId, String name, int scope, long primKey) + throws PortalException, SystemException { + + deleteResource(companyId, name, scope, String.valueOf(primKey), null); + } + + public void deleteResource( + long companyId, String name, int scope, String primKey) + throws PortalException, SystemException { + + deleteResource(companyId, name, scope, primKey, null); + } + + @Override + public void deleteResource(Resource resource) throws SystemException { + + // Permissions + + List permissions = permissionPersistence.findByResourceId( + resource.getResourceId()); + + for (Permission permission : permissions) { + orgGroupPermissionPersistence.removeByPermissionId( + permission.getPermissionId()); + } + + permissionPersistence.removeByResourceId(resource.getResourceId()); + + // Resource + + resourcePersistence.remove(resource); + } + + public void deleteResources(String name) throws SystemException { + List resources = resourceFinder.findByName(name); + + for (Resource resource : resources) { + deleteResource(resource); + } + } + + public Resource fetchResource( + long companyId, String name, int scope, String primKey) + throws SystemException { + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + return getResource_6(companyId, name, scope, primKey); + } + else { + return fetchResource_1to5(companyId, name, scope, primKey); + } + } + + public long getLatestResourceId() throws SystemException { + List resources = resourcePersistence.findAll( + 0, 1, new ResourceComparator()); + + if (resources.size() == 0) { + return 0; + } + else { + Resource resource = resources.get(0); + + return resource.getResourceId(); + } + } + + @Override + public Resource getResource(long resourceId) + throws PortalException, SystemException { + + return resourcePersistence.findByPrimaryKey(resourceId); + } + + public Resource getResource( + long companyId, String name, int scope, String primKey) + throws PortalException, SystemException { + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + return getResource_6(companyId, name, scope, primKey); + } + else { + return getResource_1to5(companyId, name, scope, primKey); + } + } + + public List getResources() throws SystemException { + return resourcePersistence.findAll(); + } + + public void updateModelResources( + AuditedModel auditedModel, ServiceContext serviceContext) + throws PortalException, SystemException { + + ClassedModel classedModel = (ClassedModel)auditedModel; + + updateResources( + auditedModel.getCompanyId(), getGroupId(auditedModel), + classedModel.getModelClassName(), + String.valueOf(classedModel.getPrimaryKeyObj()), + serviceContext.getGroupPermissions(), + serviceContext.getGuestPermissions(), + getPermissionedModel(auditedModel)); + } + + public void updateResources( + long companyId, long groupId, String name, long primKey, + String[] groupPermissions, String[] guestPermissions) + throws PortalException, SystemException { + + updateResources( + companyId, groupId, name, String.valueOf(primKey), groupPermissions, + guestPermissions, null); + } + + public void updateResources( + long companyId, long groupId, String name, String primKey, + String[] groupPermissions, String[] guestPermissions) + throws PortalException, SystemException { + + updateResources( + companyId, groupId, name, primKey, groupPermissions, + guestPermissions, null); + } + + public void updateResources( + long companyId, String name, int scope, String primKey, + String newPrimKey) + throws PortalException, SystemException { + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + if (resourceBlockLocalService.isSupported(name)) { + + // Assuming that this method is used when the primary key of an + // existing record is changed, then nothing needs to happen + // here, as it should still have its resource block ID. + + } + else { + updateResources_6(companyId, name, scope, primKey, newPrimKey); + } + } + else { + updateResources_1to5(companyId, name, scope, primKey, newPrimKey); + } + } + + protected void addGroupPermissions( + long companyId, long groupId, long userId, String name, + Resource resource, boolean portletActions, + PermissionedModel permissionedModel) + throws PortalException, SystemException { + + List actions = null; + + if (portletActions) { + actions = ResourceActionsUtil.getPortletResourceGroupDefaultActions( + name); + } + else { + actions = ResourceActionsUtil.getModelResourceGroupDefaultActions( + name); + } + + String[] actionIds = actions.toArray(new String[actions.size()]); + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + if (resourceBlockLocalService.isSupported(name)) { + addGroupPermissions_6Blocks( + groupId, resource, actions, permissionedModel); + } + else { + addGroupPermissions_6(groupId, resource, actionIds); + } + } + else { + addGroupPermissions_1to5( + companyId, groupId, userId, name, resource, portletActions, + actionIds); + } + } + + protected void addGroupPermissions_1to5( + long companyId, long groupId, long userId, String name, + Resource resource, boolean portletActions, String[] actionIds) + throws PortalException, SystemException { + + long resourceId = resource.getResourceId(); + String primKey = resource.getPrimKey(); + + List groupPermissionsList = + permissionLocalService.getPermissions( + companyId, actionIds, resourceId); + + PermissionsListFilter permissionsListFilter = + PermissionsListFilterFactory.getInstance(); + + groupPermissionsList = permissionsListFilter.filterGroupPermissions( + companyId, groupId, userId, name, primKey, portletActions, + groupPermissionsList); + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { + Role role = roleLocalService.getDefaultGroupRole(groupId); + + rolePersistence.addPermissions( + role.getRoleId(), groupPermissionsList); + } + else { + groupPersistence.addPermissions(groupId, groupPermissionsList); + } + } + + protected void addGroupPermissions_6( + long groupId, Resource resource, String[] actionIds) + throws PortalException, SystemException { + + Role role = roleLocalService.getDefaultGroupRole(groupId); + + resourcePermissionLocalService.setResourcePermissions( + resource.getCompanyId(), resource.getName(), resource.getScope(), + resource.getPrimKey(), role.getRoleId(), actionIds); + } + + protected void addGroupPermissions_6Blocks( + long groupId, Resource resource, List actionIds, + PermissionedModel permissionedModel) + throws PortalException, SystemException { + + if (permissionedModel == null) { + throw new IllegalArgumentException("Permissioned model is null"); + } + + // Scope is assumed to always be individual + + Role role = roleLocalService.getDefaultGroupRole(groupId); + + resourceBlockLocalService.setIndividualScopePermissions( + resource.getCompanyId(), groupId, resource.getName(), + permissionedModel, role.getRoleId(), actionIds); + } + + protected void addGuestPermissions( + long companyId, long groupId, long userId, String name, + Resource resource, boolean portletActions, + PermissionedModel permissionedModel) + throws PortalException, SystemException { + + List actions = null; + + if (portletActions) { + actions = ResourceActionsUtil.getPortletResourceGuestDefaultActions( + name); + } + else { + actions = ResourceActionsUtil.getModelResourceGuestDefaultActions( + name); + } + + String[] actionIds = actions.toArray(new String[actions.size()]); + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + if (resourceBlockLocalService.isSupported(name)) { + addGuestPermissions_6Blocks( + companyId, groupId, resource, actions, permissionedModel); + } + else { + addGuestPermissions_6(companyId, resource, actionIds); + } + } + else { + addGuestPermissions_1to5( + companyId, groupId, userId, name, resource, portletActions, + actionIds); + } + } + + protected void addGuestPermissions_1to5( + long companyId, long groupId, long userId, String name, + Resource resource, boolean portletActions, String[] actionIds) + throws PortalException, SystemException { + + List guestPermissionsList = + permissionLocalService.getPermissions( + companyId, actionIds, resource.getResourceId()); + + PermissionsListFilter permissionsListFilter = + PermissionsListFilterFactory.getInstance(); + + guestPermissionsList = permissionsListFilter.filterGuestPermissions( + companyId, groupId, userId, name, resource.getPrimKey(), + portletActions, guestPermissionsList); + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { + Role guestRole = roleLocalService.getRole( + companyId, RoleConstants.GUEST); + + rolePersistence.addPermissions( + guestRole.getRoleId(), guestPermissionsList); + } + else { + long defaultUserId = userLocalService.getDefaultUserId(companyId); + + userPersistence.addPermissions(defaultUserId, guestPermissionsList); + } + } + + protected void addGuestPermissions_6( + long companyId, Resource resource, String[] actionIds) + throws PortalException, SystemException { + + Role guestRole = roleLocalService.getRole( + companyId, RoleConstants.GUEST); + + resourcePermissionLocalService.setResourcePermissions( + resource.getCompanyId(), resource.getName(), resource.getScope(), + resource.getPrimKey(), guestRole.getRoleId(), actionIds); + } + + protected void addGuestPermissions_6Blocks( + long companyId, long groupId, Resource resource, + List actionIds, PermissionedModel permissionedModel) + throws PortalException, SystemException { + + if (permissionedModel == null) { + throw new IllegalArgumentException("Permissioned model is null"); + } + + // Scope is assumed to always be individual + + Role guestRole = roleLocalService.getRole( + companyId, RoleConstants.GUEST); + + resourceBlockLocalService.setIndividualScopePermissions( + resource.getCompanyId(), groupId, resource.getName(), + permissionedModel, guestRole.getRoleId(), actionIds); + } + + protected void addModelResources( + long companyId, long groupId, long userId, String name, + String primKey, String[] groupPermissions, + String[] guestPermissions, PermissionedModel permissionedModel) + throws PortalException, SystemException { + + if (!PermissionThreadLocal.isAddResource()) { + return; + } + + validate(name, false); + + // Company + + addResource( + companyId, name, ResourceConstants.SCOPE_COMPANY, + String.valueOf(companyId)); + + // Guest + + Group guestGroup = groupLocalService.getGroup( + companyId, GroupConstants.GUEST); + + addResource( + companyId, name, ResourceConstants.SCOPE_GROUP, + String.valueOf(guestGroup.getGroupId())); + + // Group + + if ((groupId > 0) && (guestGroup.getGroupId() != groupId)) { + addResource( + companyId, name, ResourceConstants.SCOPE_GROUP, + String.valueOf(groupId)); + } + + if (primKey == null) { + return; + } + + // Individual + + Resource resource = addResource( + companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey); + + // Permissions + + boolean flushEnabled = PermissionThreadLocal.isFlushEnabled(); + + PermissionThreadLocal.setIndexEnabled(false); + + try { + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + addModelResources_6( + companyId, groupId, userId, resource, groupPermissions, + guestPermissions, permissionedModel); + } + else { + addModelResources_1to5( + companyId, groupId, userId, resource, groupPermissions, + guestPermissions); + } + } + finally { + PermissionThreadLocal.setIndexEnabled(flushEnabled); + + PermissionCacheUtil.clearCache(); + + SearchEngineUtil.updatePermissionFields(name, primKey); + } + } + + protected void addModelResources_1to5( + long companyId, long groupId, long userId, Resource resource, + String[] groupPermissions, String[] guestPermissions) + throws PortalException, SystemException { + + long defaultUserId = userLocalService.getDefaultUserId(companyId); + + PermissionsListFilter permissionsListFilter = + PermissionsListFilterFactory.getInstance(); + + List permissionsList = + permissionLocalService.addPermissions( + companyId, resource.getName(), resource.getResourceId(), false); + + List userPermissionsList = + permissionsListFilter.filterUserPermissions( + companyId, groupId, userId, resource.getName(), + resource.getPrimKey(), false, permissionsList); + + filterOwnerPermissions(resource.getName(), userPermissionsList); + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { + + // Owner permissions + + Role ownerRole = roleLocalService.getRole( + companyId, RoleConstants.OWNER); + + rolePersistence.addPermissions( + ownerRole.getRoleId(), userPermissionsList); + } + else { + + // User permissions + + if ((userId > 0) && (userId != defaultUserId)) { + userPersistence.addPermissions(userId, userPermissionsList); + } + } + + // Group permissions + + if (groupId > 0) { + if (groupPermissions == null) { + groupPermissions = new String[0]; + } + + List groupPermissionsList = + permissionLocalService.getPermissions( + companyId, groupPermissions, resource.getResourceId()); + + groupPermissionsList = permissionsListFilter.filterGroupPermissions( + companyId, groupId, userId, resource.getName(), + resource.getPrimKey(), false, groupPermissionsList); + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { + Role role = roleLocalService.getDefaultGroupRole(groupId); + + rolePersistence.addPermissions( + role.getRoleId(), groupPermissionsList); + } + else { + groupPersistence.addPermissions(groupId, groupPermissionsList); + } + } + + // Guest permissions + + if (guestPermissions == null) { + guestPermissions = new String[0]; + } + + List guestPermissionsList = + permissionLocalService.getPermissions( + companyId, guestPermissions, resource.getResourceId()); + + guestPermissionsList = permissionsListFilter.filterGuestPermissions( + companyId, groupId, userId, resource.getName(), + resource.getPrimKey(), false, guestPermissionsList); + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { + Role guestRole = roleLocalService.getRole( + companyId, RoleConstants.GUEST); + + rolePersistence.addPermissions( + guestRole.getRoleId(), guestPermissionsList); + } + else { + userPersistence.addPermissions(defaultUserId, guestPermissionsList); + } + } + + protected void addModelResources_6( + long companyId, long groupId, long userId, Resource resource, + String[] groupPermissions, String[] guestPermissions, + PermissionedModel permissionedModel) + throws PortalException, SystemException { + + // Owner permissions + + Role ownerRole = roleLocalService.getRole( + companyId, RoleConstants.OWNER); + + List ownerActionIds = + ResourceActionsUtil.getModelResourceActions(resource.getName()); + + ownerActionIds = ListUtil.copy(ownerActionIds); + + filterOwnerActions(resource.getName(), ownerActionIds); + + String[] ownerPermissions = ownerActionIds.toArray( + new String[ownerActionIds.size()]); + + // Group permissions + + Role defaultGroupRole = null; + + if (groupId > 0) { + defaultGroupRole = roleLocalService.getDefaultGroupRole(groupId); + + if (groupPermissions == null) { + groupPermissions = new String[0]; + } + } + + // Guest permissions + + Role guestRole = roleLocalService.getRole( + companyId, RoleConstants.GUEST); + + if (guestPermissions == null) { + guestPermissions = new String[0]; + } + + if (resourceBlockLocalService.isSupported(resource.getName())) { + + if (permissionedModel == null) { + throw new IllegalArgumentException( + "Permissioned model is null"); + } + + // Scope is assumed to always be individual + + resourceBlockLocalService.setIndividualScopePermissions( + resource.getCompanyId(), groupId, resource.getName(), + permissionedModel, ownerRole.getRoleId(), ownerActionIds); + + if (groupId > 0) { + resourceBlockLocalService.setIndividualScopePermissions( + resource.getCompanyId(), groupId, resource.getName(), + permissionedModel, defaultGroupRole.getRoleId(), + Arrays.asList(groupPermissions)); + } + + resourceBlockLocalService.setIndividualScopePermissions( + resource.getCompanyId(), groupId, resource.getName(), + permissionedModel, guestRole.getRoleId(), + Arrays.asList(guestPermissions)); + } + else { + resourcePermissionLocalService.setOwnerResourcePermissions( + resource.getCompanyId(), resource.getName(), + resource.getScope(), resource.getPrimKey(), + ownerRole.getRoleId(), userId, ownerPermissions); + + if (groupId > 0) { + resourcePermissionLocalService.setResourcePermissions( + resource.getCompanyId(), resource.getName(), + resource.getScope(), resource.getPrimKey(), + defaultGroupRole.getRoleId(), groupPermissions); + } + + resourcePermissionLocalService.setResourcePermissions( + resource.getCompanyId(), resource.getName(), + resource.getScope(), resource.getPrimKey(), + guestRole.getRoleId(), guestPermissions); + } + } + + protected Resource addResource_1to5( + long companyId, String name, int scope, String primKey) + throws SystemException { + + ResourceCode resourceCode = resourceCodeLocalService.getResourceCode( + companyId, name, scope); + + long codeId = resourceCode.getCodeId(); + + Resource resource = resourcePersistence.fetchByC_P(codeId, primKey); + + if (resource == null) { + long resourceId = counterLocalService.increment( + Resource.class.getName()); + + resource = resourcePersistence.create(resourceId); + + resource.setCodeId(codeId); + resource.setPrimKey(primKey); + + try { + resourcePersistence.update(resource, false); + } + catch (SystemException se) { + if (_log.isWarnEnabled()) { + _log.warn( + "Add failed, fetch {codeId=" + codeId + ", primKey=" + + primKey + "}"); + } + + resource = resourcePersistence.fetchByC_P( + codeId, primKey, false); + + if (resource == null) { + throw se; + } + } + } + + return resource; + } + + protected Resource addResource_6( + long companyId, String name, int scope, String primKey) { + + Resource resource = new ResourceImpl(); + + resource.setCompanyId(companyId); + resource.setName(name); + resource.setScope(scope); + resource.setPrimKey(primKey); + + return resource; + } + + protected void addResources( + long companyId, long groupId, long userId, String name, + String primKey, boolean portletActions, boolean addGroupPermissions, + boolean addGuestPermissions, PermissionedModel permissionedModel) + throws PortalException, SystemException { + + if (!PermissionThreadLocal.isAddResource()) { + return; + } + + validate(name, portletActions); + + // Company + + addResource( + companyId, name, ResourceConstants.SCOPE_COMPANY, + String.valueOf(companyId)); + + if (groupId > 0) { + addResource( + companyId, name, ResourceConstants.SCOPE_GROUP, + String.valueOf(groupId)); + } + + if (primKey == null) { + return; + } + + // Individual + + Resource resource = addResource( + companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey); + + // Permissions + + boolean flushEnabled = PermissionThreadLocal.isFlushEnabled(); + + PermissionThreadLocal.setIndexEnabled(false); + + List resourcePermissions = + resourcePermissionPersistence.findByC_N_S_P( + companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey); + + ResourcePermissionsThreadLocal.setResourcePermissions( + resourcePermissions); + + try { + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + addResources_6( + companyId, groupId, userId, resource, portletActions, + permissionedModel); + } + else { + addResources_1to5( + companyId, groupId, userId, resource, portletActions); + } + + // Group permissions + + if ((groupId > 0) && addGroupPermissions) { + addGroupPermissions( + companyId, groupId, userId, name, resource, portletActions, + permissionedModel); + } + + // Guest permissions + + if (addGuestPermissions) { + + // Don't add guest permissions when you've already added group + // permissions and the given group is the guest group. + + addGuestPermissions( + companyId, groupId, userId, name, resource, portletActions, + permissionedModel); + } + } + finally { + ResourcePermissionsThreadLocal.setResourcePermissions(null); + + PermissionThreadLocal.setIndexEnabled(flushEnabled); + + PermissionCacheUtil.clearCache(); + + SearchEngineUtil.updatePermissionFields(name, primKey); + } + } + + protected void addResources_1to5( + long companyId, long groupId, long userId, Resource resource, + boolean portletActions) + throws PortalException, SystemException { + + List permissionsList = + permissionLocalService.addPermissions( + companyId, resource.getName(), resource.getResourceId(), + portletActions); + + PermissionsListFilter permissionsListFilter = + PermissionsListFilterFactory.getInstance(); + + List userPermissionsList = + permissionsListFilter.filterUserPermissions( + companyId, groupId, userId, resource.getName(), + resource.getPrimKey(), portletActions, permissionsList); + + filterOwnerPermissions(resource.getName(), userPermissionsList); + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) { + + // Owner permissions + + Role ownerRole = roleLocalService.getRole( + companyId, RoleConstants.OWNER); + + rolePersistence.addPermissions( + ownerRole.getRoleId(), userPermissionsList); + } + else { + + // User permissions + + long defaultUserId = userLocalService.getDefaultUserId(companyId); + + if ((userId > 0) && (userId != defaultUserId)) { + userPersistence.addPermissions(userId, userPermissionsList); + } + } + } + + protected void addResources_6( + long companyId, long groupId, long userId, Resource resource, + boolean portletActions, PermissionedModel permissionedModel) + throws PortalException, SystemException { + + List actionIds = null; + + if (portletActions) { + actionIds = ResourceActionsUtil.getPortletResourceActions( + resource.getName()); + } + else { + actionIds = ResourceActionsUtil.getModelResourceActions( + resource.getName()); + + actionIds = ListUtil.copy(actionIds); + + filterOwnerActions(resource.getName(), actionIds); + } + + Role role = roleLocalService.getRole(companyId, RoleConstants.OWNER); + + if (resourceBlockLocalService.isSupported(resource.getName())) { + if (permissionedModel == null) { + throw new IllegalArgumentException( + "Permissioned model is null"); + } + + // Scope is assumed to always be individual + + resourceBlockLocalService.setIndividualScopePermissions( + resource.getCompanyId(), groupId, resource.getName(), + permissionedModel, role.getRoleId(), actionIds); + } + else { + resourcePermissionLocalService.setOwnerResourcePermissions( + resource.getCompanyId(), resource.getName(), + resource.getScope(), resource.getPrimKey(), role.getRoleId(), + userId, actionIds.toArray(new String[actionIds.size()])); + } + } + + protected void deleteResource( + long companyId, String name, int scope, String primKey, + PermissionedModel permissionedModel) + throws PortalException, SystemException{ + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + if (resourceBlockLocalService.isSupported(name)) { + if (permissionedModel == null) { + throw new IllegalArgumentException( + "Permissioned model is null"); + } + + resourceBlockLocalService.releasePermissionedModelResourceBlock( + permissionedModel); + + return; + } + else { + resourcePermissionLocalService.deleteResourcePermissions( + companyId, name, scope, primKey); + + return; + } + } + + try { + Resource resource = getResource(companyId, name, scope, primKey); + + deleteResource(resource.getResourceId()); + } + catch (NoSuchResourceException nsre) { + if (_log.isWarnEnabled()) { + _log.warn(nsre); + } + } + } + + protected Resource fetchResource_1to5( + long companyId, String name, int scope, String primKey) + throws SystemException { + + ResourceCode resourceCode = resourceCodeLocalService.getResourceCode( + companyId, name, scope); + + return resourcePersistence.fetchByC_P( + resourceCode.getCodeId(), primKey); + } + + protected void filterOwnerActions(String name, List actionIds) { + List defaultOwnerActions = + ResourceActionsUtil.getModelResourceOwnerDefaultActions(name); + + if (defaultOwnerActions.isEmpty()) { + return; + } + + Iterator itr = actionIds.iterator(); + + while (itr.hasNext()) { + String actionId = itr.next(); + + if (!defaultOwnerActions.contains(actionId)) { + itr.remove(); + } + } + } + + protected void filterOwnerPermissions( + String name, List permissions) { + + List defaultOwnerActions = + ResourceActionsUtil.getModelResourceOwnerDefaultActions(name); + + if (defaultOwnerActions.isEmpty()) { + return; + } + + Iterator itr = permissions.iterator(); + + while (itr.hasNext()) { + Permission permission = itr.next(); + + String actionId = permission.getActionId(); + + if (!defaultOwnerActions.contains(actionId)) { + itr.remove(); + } + } + } + + protected long getGroupId(AuditedModel auditedModel) { + long groupId = 0; + + if (auditedModel instanceof GroupedModel) { + GroupedModel groupedModel = (GroupedModel)auditedModel; + + groupId = groupedModel.getGroupId(); + } + + return groupId; + } + + protected PermissionedModel getPermissionedModel( + AuditedModel auditedModel) { + + PermissionedModel permissionedModel = null; + + if (auditedModel instanceof PermissionedModel) { + permissionedModel = (PermissionedModel)auditedModel; + } + + return permissionedModel; + } + + protected Resource getResource_1to5( + long companyId, String name, int scope, String primKey) + throws PortalException, SystemException { + + ResourceCode resourceCode = resourceCodeLocalService.getResourceCode( + companyId, name, scope); + + return resourcePersistence.findByC_P(resourceCode.getCodeId(), primKey); + } + + protected Resource getResource_6( + long companyId, String name, int scope, String primKey) { + + Resource resource = new ResourceImpl(); + + resource.setCompanyId(companyId); + resource.setName(name); + resource.setScope(scope); + resource.setPrimKey(primKey); + + return resource; + } + + protected void updateResources( + long companyId, long groupId, String name, String primKey, + String[] groupPermissions, String[] guestPermissions, + PermissionedModel permissionedModel) + throws PortalException, SystemException { + + Resource resource = getResource( + companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey); + + if (groupPermissions == null) { + groupPermissions = new String[0]; + } + + if (guestPermissions == null) { + guestPermissions = new String[0]; + } + + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + if (resourceBlockLocalService.isSupported(name)) { + updateResources_6Blocks( + companyId, groupId, resource, groupPermissions, + guestPermissions, permissionedModel); + } + else { + updateResources_6( + companyId, groupId, resource, groupPermissions, + guestPermissions); + } + } + else { + updateResources_1to5( + companyId, groupId, resource, groupPermissions, + guestPermissions); + } + } + + protected void updateResources_1to5( + long companyId, long groupId, Resource resource, + String[] groupPermissions, String[] guestPermissions) + throws PortalException, SystemException { + + Role role = roleLocalService.getDefaultGroupRole(groupId); + + permissionLocalService.setRolePermissions( + role.getRoleId(), groupPermissions, resource.getResourceId()); + + role = roleLocalService.getRole(companyId, RoleConstants.GUEST); + + permissionLocalService.setRolePermissions( + role.getRoleId(), guestPermissions, resource.getResourceId()); + } + + protected void updateResources_1to5( + long companyId, String name, int scope, String primKey, + String newPrimKey) + throws PortalException, SystemException { + + Resource resource = getResource(companyId, name, scope, primKey); + + resource.setPrimKey(newPrimKey); + + resourcePersistence.update(resource, false); + } + + protected void updateResources_6( + long companyId, long groupId, Resource resource, + String[] groupPermissions, String[] guestPermissions) + throws PortalException, SystemException { + + Role role = roleLocalService.getDefaultGroupRole(groupId); + + resourcePermissionLocalService.setResourcePermissions( + resource.getCompanyId(), resource.getName(), resource.getScope(), + resource.getPrimKey(), role.getRoleId(), groupPermissions); + + role = roleLocalService.getRole(companyId, RoleConstants.GUEST); + + resourcePermissionLocalService.setResourcePermissions( + resource.getCompanyId(), resource.getName(), resource.getScope(), + resource.getPrimKey(), role.getRoleId(), guestPermissions); + } + + protected void updateResources_6( + long companyId, String name, int scope, String primKey, + String newPrimKey) + throws SystemException { + + List resourcePermissions = + resourcePermissionLocalService.getResourcePermissions( + companyId, name, scope, primKey); + + for (ResourcePermission resourcePermission : resourcePermissions) { + resourcePermission.setPrimKey(newPrimKey); + + resourcePermissionPersistence.update(resourcePermission, false); + } + } + + protected void updateResources_6Blocks( + long companyId, long groupId, Resource resource, + String[] groupPermissions, String[] guestPermissions, + PermissionedModel permissionedModel) + throws PortalException, SystemException { + + if (permissionedModel == null) { + throw new IllegalArgumentException("Permissioned model is null"); + } + + // Scope is assumed to always be individual + + Role role = roleLocalService.getDefaultGroupRole(groupId); + + resourceBlockLocalService.setIndividualScopePermissions( + companyId, groupId, resource.getName(), permissionedModel, + role.getRoleId(), Arrays.asList(groupPermissions)); + + role = roleLocalService.getRole(companyId, RoleConstants.GUEST); + + resourceBlockLocalService.setIndividualScopePermissions( + companyId, groupId, resource.getName(), permissionedModel, + role.getRoleId(), Arrays.asList(guestPermissions)); + } + + protected void validate(String name, boolean portletActions) + throws PortalException { + + List actions = null; + + if (portletActions) { + actions = ResourceActionsUtil.getPortletResourceActions(name); + } + else { + actions = ResourceActionsUtil.getModelResourceActions(name); + } + + if (actions.size() == 0) { + throw new ResourceActionsException( + "There are no actions associated with the resource " + name); + } + } + + private static Log _log = LogFactoryUtil.getLog( + ResourceLocalServiceImpl.class); + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portal/service/impl/SubscriptionLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/SubscriptionLocalServiceImpl.java index 97c72fa6c526fd..f3ac3eee2ac7e0 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/SubscriptionLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/SubscriptionLocalServiceImpl.java @@ -89,8 +89,8 @@ public Subscription addSubscription( } catch (Exception e) { assetEntryLocalService.updateEntry( - userId, groupId, className, classPK, null, 0, - null, null, false, null, null, null, null, null, + userId, groupId, className, classPK, null, 0, null, null, + false, null, null, null, null, null, String.valueOf(groupId), null, null, null, null, 0, 0, null, false); } diff --git a/portal-impl/src/com/liferay/portal/service/impl/ThemeLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/ThemeLocalServiceImpl.java index bcc3318fe2c8dd..e9fb1a18aaa1a4 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/ThemeLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/ThemeLocalServiceImpl.java @@ -706,8 +706,8 @@ private Set _readThemes( if (customElement != null) { layoutTemplateLocalService.readLayoutTemplate( - servletContextName, servletContext, null, - customElement, false, themeId, pluginPackage); + servletContextName, servletContext, null, customElement, + false, themeId, pluginPackage); } } diff --git a/portal-impl/src/com/liferay/portal/service/impl/UserLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/UserLocalServiceImpl.java index 84eb21351c762b..2c47632c24f0c0 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/UserLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/UserLocalServiceImpl.java @@ -1460,8 +1460,8 @@ public void completeUserRegistration( mailService.addUser( user.getCompanyId(), user.getUserId(), mailPassword, - user.getFirstName(), user.getMiddleName(), - user.getLastName(), user.getEmailAddress()); + user.getFirstName(), user.getMiddleName(), user.getLastName(), + user.getEmailAddress()); } boolean sendEmail = GetterUtil.getBoolean( @@ -2981,9 +2981,9 @@ public Hits search( */ public List search( long companyId, String firstName, String middleName, - String lastName, String screenName, String emailAddress, - int status, LinkedHashMap params, - boolean andSearch, int start, int end, OrderByComparator obc) + String lastName, String screenName, String emailAddress, int status, + LinkedHashMap params, boolean andSearch, int start, + int end, OrderByComparator obc) throws SystemException { return userFinder.findByC_FN_MN_LN_SN_EA_S( @@ -3032,9 +3032,9 @@ public List search( */ public Hits search( long companyId, String firstName, String middleName, - String lastName, String screenName, String emailAddress, - int status, LinkedHashMap params, - boolean andSearch, int start, int end, Sort sort) + String lastName, String screenName, String emailAddress, int status, + LinkedHashMap params, boolean andSearch, int start, + int end, Sort sort) throws SystemException { return search( @@ -3089,9 +3089,8 @@ public int searchCount( */ public int searchCount( long companyId, String firstName, String middleName, - String lastName, String screenName, String emailAddress, - int status, LinkedHashMap params, - boolean andSearch) + String lastName, String screenName, String emailAddress, int status, + LinkedHashMap params, boolean andSearch) throws SystemException { return userFinder.countByC_FN_MN_LN_SN_EA_S( diff --git a/portal-impl/src/com/liferay/portal/service/impl/UserServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/UserServiceImpl.java index 3e8b59004f782d..7db25e444f5261 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/UserServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/UserServiceImpl.java @@ -952,8 +952,7 @@ public void unsetOrganizationUsers(long organizationId, long[] userIds) throws PortalException, SystemException { OrganizationPermissionUtil.check( - getPermissionChecker(), organizationId, - ActionKeys.ASSIGN_MEMBERS); + getPermissionChecker(), organizationId, ActionKeys.ASSIGN_MEMBERS); userLocalService.unsetOrganizationUsers(organizationId, userIds); } @@ -1422,8 +1421,8 @@ public User updateUser( comments, firstName, middleName, lastName, prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear, smsSn, aimSn, facebookSn, icqSn, jabberSn, msnSn, mySpaceSn, skypeSn, twitterSn, ymSn, - jobTitle, groupIds, organizationIds, roleIds, - userGroupRoles, userGroupIds, serviceContext); + jobTitle, groupIds, organizationIds, roleIds, userGroupRoles, + userGroupIds, serviceContext); return user; } diff --git a/portal-impl/src/com/liferay/portal/service/impl/WebsiteLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/WebsiteLocalServiceImpl.java index b6e787a3ca2cb5..9746265ab2f756 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/WebsiteLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/WebsiteLocalServiceImpl.java @@ -43,8 +43,7 @@ public Website addWebsite( Date now = new Date(); validate( - 0, user.getCompanyId(), classNameId, classPK, url, typeId, - primary); + 0, user.getCompanyId(), classNameId, classPK, url, typeId, primary); long websiteId = counterLocalService.increment(); diff --git a/portal-impl/src/com/liferay/portal/service/impl/WorkflowDefinitionLinkLocalServiceImpl.java b/portal-impl/src/com/liferay/portal/service/impl/WorkflowDefinitionLinkLocalServiceImpl.java index e30443cc1d4784..4414473744b612 100644 --- a/portal-impl/src/com/liferay/portal/service/impl/WorkflowDefinitionLinkLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portal/service/impl/WorkflowDefinitionLinkLocalServiceImpl.java @@ -105,8 +105,8 @@ public WorkflowDefinitionLink getDefaultWorkflowDefinitionLink( long classNameId = PortalUtil.getClassNameId(className); return workflowDefinitionLinkPersistence.findByG_C_C_C_T( - WorkflowConstants.DEFAULT_GROUP_ID, companyId, classNameId, - classPK, typePK); + WorkflowConstants.DEFAULT_GROUP_ID, companyId, classNameId, classPK, + typePK); } public WorkflowDefinitionLink getWorkflowDefinitionLink( diff --git a/portal-impl/src/com/liferay/portal/service/permission/AccountPermissionImpl.java b/portal-impl/src/com/liferay/portal/service/permission/AccountPermissionImpl.java index 44ccdcd26a44b8..8e798efccbc9ac 100644 --- a/portal-impl/src/com/liferay/portal/service/permission/AccountPermissionImpl.java +++ b/portal-impl/src/com/liferay/portal/service/permission/AccountPermissionImpl.java @@ -53,8 +53,7 @@ public boolean contains( long groupId = 0; return permissionChecker.hasPermission( - groupId, Account.class.getName(), account.getAccountId(), - actionId); + groupId, Account.class.getName(), account.getAccountId(), actionId); } public boolean contains( diff --git a/portal-impl/src/com/liferay/portal/service/permission/GroupPermissionImpl.java b/portal-impl/src/com/liferay/portal/service/permission/GroupPermissionImpl.java index 996e75d25d566e..0cafcced219583 100644 --- a/portal-impl/src/com/liferay/portal/service/permission/GroupPermissionImpl.java +++ b/portal-impl/src/com/liferay/portal/service/permission/GroupPermissionImpl.java @@ -31,8 +31,7 @@ public class GroupPermissionImpl implements GroupPermission { public void check( - PermissionChecker permissionChecker, long groupId, - String actionId) + PermissionChecker permissionChecker, long groupId, String actionId) throws PortalException, SystemException { if (!contains(permissionChecker, groupId, actionId)) { diff --git a/portal-impl/src/com/liferay/portal/service/permission/LayoutBranchPermissionImpl.java b/portal-impl/src/com/liferay/portal/service/permission/LayoutBranchPermissionImpl.java index f7997a98b8702e..351000c6ed2e4e 100644 --- a/portal-impl/src/com/liferay/portal/service/permission/LayoutBranchPermissionImpl.java +++ b/portal-impl/src/com/liferay/portal/service/permission/LayoutBranchPermissionImpl.java @@ -28,8 +28,8 @@ public class LayoutBranchPermissionImpl implements LayoutBranchPermission { public void check( - PermissionChecker permissionChecker, - LayoutBranch layoutBranch, String actionId) + PermissionChecker permissionChecker, LayoutBranch layoutBranch, + String actionId) throws PortalException { if (!contains(permissionChecker, layoutBranch, actionId)) { diff --git a/portal-impl/src/com/liferay/portal/service/permission/LayoutPermissionImpl.java b/portal-impl/src/com/liferay/portal/service/permission/LayoutPermissionImpl.java index 11f50e60aefe74..b99ce115048aa2 100644 --- a/portal-impl/src/com/liferay/portal/service/permission/LayoutPermissionImpl.java +++ b/portal-impl/src/com/liferay/portal/service/permission/LayoutPermissionImpl.java @@ -411,8 +411,7 @@ else if (group.isStagingGroup()) { permissionChecker, group.getGroupId(), ActionKeys.MANAGE_LAYOUTS) || GroupPermissionUtil.contains( - permissionChecker, group.getGroupId(), - ActionKeys.UPDATE)) { + permissionChecker, group.getGroupId(), ActionKeys.UPDATE)) { return true; } diff --git a/portal-impl/src/com/liferay/portal/service/persistence/GroupFinderImpl.java b/portal-impl/src/com/liferay/portal/service/persistence/GroupFinderImpl.java index e5d62e41961168..550168454894d2 100644 --- a/portal-impl/src/com/liferay/portal/service/persistence/GroupFinderImpl.java +++ b/portal-impl/src/com/liferay/portal/service/persistence/GroupFinderImpl.java @@ -557,8 +557,8 @@ companyId, _getGroupOrganizationClassNameIds(), name, realName, public List findByC_C_N_D( long companyId, long[] classNameIds, String name, String realName, - String description, LinkedHashMap params, - int start, int end, OrderByComparator obc) + String description, LinkedHashMap params, int start, + int end, OrderByComparator obc) throws SystemException { name = StringUtil.lowerCase(name); @@ -898,8 +898,7 @@ protected String replaceJoinAndWhere( return StringUtil.replace( sql, new String[] { - "[$JOIN$]", - "[$WHERE$]" + "[$JOIN$]", "[$WHERE$]" }, new String[] { StringPool.BLANK, diff --git a/portal-impl/src/com/liferay/portal/service/persistence/OrganizationFinderImpl.java b/portal-impl/src/com/liferay/portal/service/persistence/OrganizationFinderImpl.java index 18bb5a0ab133c0..60f08506350468 100644 --- a/portal-impl/src/com/liferay/portal/service/persistence/OrganizationFinderImpl.java +++ b/portal-impl/src/com/liferay/portal/service/persistence/OrganizationFinderImpl.java @@ -87,8 +87,8 @@ public class OrganizationFinderImpl public int countByKeywords( long companyId, long parentOrganizationId, - String parentOrganizationIdComparator, String keywords, - String type, Long regionId, Long countryId, + String parentOrganizationIdComparator, String keywords, String type, + Long regionId, Long countryId, LinkedHashMap params) throws SystemException { @@ -160,9 +160,9 @@ public int countByC_PO_N_T_S_C_Z_R_C( public int countByC_PO_N_T_S_C_Z_R_C( long companyId, long parentOrganizationId, - String parentOrganizationIdComparator, String[] names, - String type, String[] streets, String[] cities, String[] zips, - Long regionId, Long countryId, LinkedHashMap params, + String parentOrganizationIdComparator, String[] names, String type, + String[] streets, String[] cities, String[] zips, Long regionId, + Long countryId, LinkedHashMap params, boolean andOperator) throws SystemException { @@ -204,20 +204,15 @@ public int countByC_PO_N_T_S_C_Z_R_C( sql, "lower(Organization_.name)", StringPool.LIKE, false, names); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street1)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street1)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street2)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street2)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street3)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street3)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.city)", StringPool.LIKE, false, - cities); + sql, "lower(Address.city)", StringPool.LIKE, false, cities); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.zip)", StringPool.LIKE, true, - zips); + sql, "lower(Address.zip)", StringPool.LIKE, true, zips); if (regionId == null) { sql = StringUtil.replace(sql, REGION_ID_SQL, StringPool.BLANK); @@ -352,8 +347,8 @@ public List findByCompanyId( public List findByKeywords( long companyId, long parentOrganizationId, - String parentOrganizationIdComparator, String keywords, - String type, Long regionId, Long countryId, + String parentOrganizationIdComparator, String keywords, String type, + Long regionId, Long countryId, LinkedHashMap params, int start, int end, OrderByComparator obc) throws SystemException { @@ -401,9 +396,9 @@ public List findByC_PO_N_T_S_C_Z_R_C( public List findByC_PO_N_T_S_C_Z_R_C( long companyId, long parentOrganizationId, - String parentOrganizationIdComparator, String[] names, - String type, String[] streets, String[] cities, String[] zips, - Long regionId, Long countryId, LinkedHashMap params, + String parentOrganizationIdComparator, String[] names, String type, + String[] streets, String[] cities, String[] zips, Long regionId, + Long countryId, LinkedHashMap params, boolean andOperator, int start, int end, OrderByComparator obc) throws SystemException { @@ -447,23 +442,17 @@ public List findByC_PO_N_T_S_C_Z_R_C( sql = StringUtil.replace(sql, "[$WHERE$]", getWhere(params)); sql = sql.concat(StringPool.CLOSE_PARENTHESIS); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Organization_.name)", StringPool.LIKE, false, - names); + sql, "lower(Organization_.name)", StringPool.LIKE, false, names); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street1)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street1)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street2)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street2)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street3)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street3)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.city)", StringPool.LIKE, false, - cities); + sql, "lower(Address.city)", StringPool.LIKE, false, cities); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.zip)", StringPool.LIKE, true, - zips); + sql, "lower(Address.zip)", StringPool.LIKE, true, zips); sql = StringUtil.replace( sql, "[$PARENT_ORGANIZATION_ID_COMPARATOR$]", parentOrganizationIdComparator); @@ -573,10 +562,9 @@ protected int countByOrganizationId( protected int countByPermissions( long companyId, long parentOrganizationId, - String parentOrganizationIdComparator, String[] names, - String type, String[] streets, String[] cities, String[] zips, - Long regionId, Long countryId, long resourceId, long groupId, - boolean andOperator) + String parentOrganizationIdComparator, String[] names, String type, + String[] streets, String[] cities, String[] zips, Long regionId, + Long countryId, long resourceId, long groupId, boolean andOperator) throws SystemException { Session session = null; @@ -652,20 +640,15 @@ protected int countByPermissions( sql, "lower(Organization_.name)", StringPool.LIKE, false, names); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street1)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street1)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street2)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street2)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street3)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street3)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.city)", StringPool.LIKE, false, - cities); + sql, "lower(Address.city)", StringPool.LIKE, false, cities); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.zip)", StringPool.LIKE, true, - zips); + sql, "lower(Address.zip)", StringPool.LIKE, true, zips); if (regionId == null) { sql = StringUtil.replace(sql, REGION_ID_SQL, StringPool.BLANK); @@ -736,10 +719,10 @@ protected int countByPermissions( protected List findByPermissions( long companyId, long parentOrganizationId, - String parentOrganizationIdComparator, String[] names, - String type, String[] streets, String[] cities, String[] zips, - Long regionId, Long countryId, long resourceId, long groupId, - boolean andOperator, int start, int end, OrderByComparator obc) + String parentOrganizationIdComparator, String[] names, String type, + String[] streets, String[] cities, String[] zips, Long regionId, + Long countryId, long resourceId, long groupId, boolean andOperator, + int start, int end, OrderByComparator obc) throws SystemException { Session session = null; @@ -816,20 +799,15 @@ protected List findByPermissions( sql, "lower(Organization_.name)", StringPool.LIKE, false, names); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street1)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street1)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street2)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street2)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.street3)", StringPool.LIKE, true, - streets); + sql, "lower(Address.street3)", StringPool.LIKE, true, streets); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.city)", StringPool.LIKE, false, - cities); + sql, "lower(Address.city)", StringPool.LIKE, false, cities); sql = CustomSQLUtil.replaceKeywords( - sql, "lower(Address.zip)", StringPool.LIKE, true, - zips); + sql, "lower(Address.zip)", StringPool.LIKE, true, zips); if (regionId == null) { sql = StringUtil.replace(sql, REGION_ID_SQL, StringPool.BLANK); diff --git a/portal-impl/src/com/liferay/portal/service/persistence/UserFinderImpl.java b/portal-impl/src/com/liferay/portal/service/persistence/UserFinderImpl.java index 6abb43099066e9..22a6f54cfc1ff8 100644 --- a/portal-impl/src/com/liferay/portal/service/persistence/UserFinderImpl.java +++ b/portal-impl/src/com/liferay/portal/service/persistence/UserFinderImpl.java @@ -186,9 +186,8 @@ public int countByKeywords( public int countByC_FN_MN_LN_SN_EA_S( long companyId, String firstName, String middleName, - String lastName, String screenName, String emailAddress, - int status, LinkedHashMap params, - boolean andOperator) + String lastName, String screenName, String emailAddress, int status, + LinkedHashMap params, boolean andOperator) throws SystemException { String[] firstNames = CustomSQLUtil.keywords(firstName); @@ -389,9 +388,9 @@ public List findByNoGroups() throws SystemException { public List findByC_FN_MN_LN_SN_EA_S( long companyId, String firstName, String middleName, - String lastName, String screenName, String emailAddress, - int status, LinkedHashMap params, - boolean andOperator, int start, int end, OrderByComparator obc) + String lastName, String screenName, String emailAddress, int status, + LinkedHashMap params, boolean andOperator, + int start, int end, OrderByComparator obc) throws SystemException { String[] firstNames = CustomSQLUtil.keywords(firstName); diff --git a/portal-impl/src/com/liferay/portal/servlet/MainServlet.java b/portal-impl/src/com/liferay/portal/servlet/MainServlet.java index d58ac923ba2c28..ed69461c91c9c7 100644 --- a/portal-impl/src/com/liferay/portal/servlet/MainServlet.java +++ b/portal-impl/src/com/liferay/portal/servlet/MainServlet.java @@ -1035,8 +1035,8 @@ protected long loginUser( session.setAttribute(Globals.LOCALE_KEY, user.getLocale()); EventsProcessorUtil.process( - PropsKeys.LOGIN_EVENTS_POST, PropsValues.LOGIN_EVENTS_POST, - request, response); + PropsKeys.LOGIN_EVENTS_POST, PropsValues.LOGIN_EVENTS_POST, request, + response); return userId; } diff --git a/portal-impl/src/com/liferay/portal/servlet/filters/dynamiccss/DynamicCSSUtil.java b/portal-impl/src/com/liferay/portal/servlet/filters/dynamiccss/DynamicCSSUtil.java index 6b5a6f0325eee4..aabbbf5e38ff3c 100644 --- a/portal-impl/src/com/liferay/portal/servlet/filters/dynamiccss/DynamicCSSUtil.java +++ b/portal-impl/src/com/liferay/portal/servlet/filters/dynamiccss/DynamicCSSUtil.java @@ -152,8 +152,7 @@ public static String parseSass( parsedContent = StringUtil.replace( parsedContent, new String[] { - "@portal_ctx@", - "@theme_image_path@" + "@portal_ctx@", "@theme_image_path@" }, new String[] { PortalUtil.getPathContext(), diff --git a/portal-impl/src/com/liferay/portal/spring/bean/BeanReferenceAnnotationBeanPostProcessor.java b/portal-impl/src/com/liferay/portal/spring/bean/BeanReferenceAnnotationBeanPostProcessor.java index 20d692f4d0eb1d..a5a41990bff239 100644 --- a/portal-impl/src/com/liferay/portal/spring/bean/BeanReferenceAnnotationBeanPostProcessor.java +++ b/portal-impl/src/com/liferay/portal/spring/bean/BeanReferenceAnnotationBeanPostProcessor.java @@ -158,8 +158,7 @@ private void _autoInject( } catch (Throwable t) { throw new BeanCreationException( - targetBeanName, "Could not inject BeanReference fields", - t); + targetBeanName, "Could not inject BeanReference fields", t); } } diff --git a/portal-impl/src/com/liferay/portal/staging/StagingImpl.java b/portal-impl/src/com/liferay/portal/staging/StagingImpl.java index 491fbbb48339eb..5c274e85d1b64c 100644 --- a/portal-impl/src/com/liferay/portal/staging/StagingImpl.java +++ b/portal-impl/src/com/liferay/portal/staging/StagingImpl.java @@ -601,8 +601,7 @@ public List getMissingParentLayouts(Layout layout, long liveGroupId) while (parentLayoutId > 0) { parentLayout = LayoutLocalServiceUtil.getLayout( - layout.getGroupId(), layout.isPrivateLayout(), - parentLayoutId); + layout.getGroupId(), layout.isPrivateLayout(), parentLayoutId); try { LayoutLocalServiceUtil.getLayoutByUuidAndGroupId( @@ -1374,8 +1373,8 @@ protected void checkDefaultLayoutSetBranches( try { LayoutSetBranchLocalServiceUtil.addLayoutSetBranch( userId, targetGroupId, false, - LayoutSetBranchConstants.MASTER_BRANCH_NAME, - description, true, LayoutSetBranchConstants.ALL_BRANCHES, + LayoutSetBranchConstants.MASTER_BRANCH_NAME, description, + true, LayoutSetBranchConstants.ALL_BRANCHES, serviceContext); } catch (LayoutSetBranchNameException lsbne) { @@ -1393,8 +1392,8 @@ protected void checkDefaultLayoutSetBranches( try { LayoutSetBranchLocalServiceUtil.addLayoutSetBranch( userId, targetGroupId, true, - LayoutSetBranchConstants.MASTER_BRANCH_NAME, - description, true, LayoutSetBranchConstants.ALL_BRANCHES, + LayoutSetBranchConstants.MASTER_BRANCH_NAME, description, + true, LayoutSetBranchConstants.ALL_BRANCHES, serviceContext); } catch (LayoutSetBranchNameException lsbne) { diff --git a/portal-impl/src/com/liferay/portal/tools/DBLoader.java b/portal-impl/src/com/liferay/portal/tools/DBLoader.java index dcfb72a9bfaae7..ce268205c7b0c9 100644 --- a/portal-impl/src/com/liferay/portal/tools/DBLoader.java +++ b/portal-impl/src/com/liferay/portal/tools/DBLoader.java @@ -62,16 +62,10 @@ public static void loadHypersonic(Connection con, String fileName) StringUtil.replace( sql, new String[] { - "\\\"", - "\\\\", - "\\n", - "\\r" + "\\\"", "\\\\", "\\n", "\\r" }, new String[] { - "\"", - "\\", - "\\u000a", - "\\u000a" + "\"", "\\", "\\u000a", "\\u000a" }); sb.setIndex(0); @@ -182,17 +176,11 @@ private void _loadDerby(Connection con, String fileName) sql, new String[] { "\\'", - "\\\"", - "\\\\", - "\\n", - "\\r" + "\\\"", "\\\\", "\\n", "\\r" }, new String[] { "''", - "\"", - "\\", - "\n", - "\r" + "\"", "\\", "\n", "\r" }); sql = sql.substring(0, sql.length() - 1); diff --git a/portal-impl/src/com/liferay/portal/tools/ExtInfoBuilder.java b/portal-impl/src/com/liferay/portal/tools/ExtInfoBuilder.java index 06f7100cce0fcc..f5bfa4f14ca803 100644 --- a/portal-impl/src/com/liferay/portal/tools/ExtInfoBuilder.java +++ b/portal-impl/src/com/liferay/portal/tools/ExtInfoBuilder.java @@ -55,12 +55,9 @@ public ExtInfoBuilder( ".svn/**", "**/.svn/**", "ext-impl/ext-impl.jar", "ext-impl/src/**", "ext-service/ext-service.jar", "ext-service/src/**", "ext-util-bridges/ext-util-bridges.jar", - "ext-util-bridges/src/**", - "ext-util-java/ext-util-java.jar", - "ext-util-java/src/**", - "ext-util-taglib/ext-util-taglib.jar", - "ext-util-taglib/src/**", - "liferay-plugin-package.properties" + "ext-util-bridges/src/**", "ext-util-java/ext-util-java.jar", + "ext-util-java/src/**", "ext-util-taglib/ext-util-taglib.jar", + "ext-util-taglib/src/**", "liferay-plugin-package.properties" }); ds.scan(); diff --git a/portal-impl/src/com/liferay/portal/tools/LangBuilder.java b/portal-impl/src/com/liferay/portal/tools/LangBuilder.java index 1172280811fa73..b5e6e3510373b9 100644 --- a/portal-impl/src/com/liferay/portal/tools/LangBuilder.java +++ b/portal-impl/src/com/liferay/portal/tools/LangBuilder.java @@ -431,8 +431,8 @@ private String _fixTranslation(String value) { value = StringUtil.replace( value.trim(), new String[] { - " ", "", "", "", "", " url ", "'", - "' ;", """, "" ;" + " ", "", "", "", "", " url ", "'", "' ;", + """, "" ;" }, new String[] { " ", "", "", "", "", " URL ", "\'", diff --git a/portal-impl/src/com/liferay/portal/upgrade/v5_0_0/UpgradeImageGallery.java b/portal-impl/src/com/liferay/portal/upgrade/v5_0_0/UpgradeImageGallery.java index e0c2294c61566d..4b036a87967dda 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v5_0_0/UpgradeImageGallery.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v5_0_0/UpgradeImageGallery.java @@ -56,8 +56,8 @@ protected void doUpgrade() throws Exception { imageIdColumn); upgradeTable = UpgradeTableFactoryUtil.getUpgradeTable( - IGImageTable.TABLE_NAME, IGImageTable.TABLE_COLUMNS, - imageIdColumn, imageNameColumn); + IGImageTable.TABLE_NAME, IGImageTable.TABLE_COLUMNS, imageIdColumn, + imageNameColumn); upgradeTable.updateTable(); } diff --git a/portal-impl/src/com/liferay/portal/upgrade/v5_2_0/UpgradePortletId.java b/portal-impl/src/com/liferay/portal/upgrade/v5_2_0/UpgradePortletId.java index 90b90378897671..1c03c95d9c0f38 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v5_2_0/UpgradePortletId.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v5_2_0/UpgradePortletId.java @@ -51,8 +51,7 @@ protected void doUpgrade() throws Exception { protected String[][] getPortletIdsArray() { return new String[][] { new String[] { - "109", - "1_WAR_webformportlet" + "109", "1_WAR_webformportlet" }, new String[] { "google_adsense_portlet_WAR_googleadsenseportlet", diff --git a/portal-impl/src/com/liferay/portal/upgrade/v5_2_0/UpgradeTags.java b/portal-impl/src/com/liferay/portal/upgrade/v5_2_0/UpgradeTags.java index 14e355fa7c8e59..5ef21f2596fd32 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v5_2_0/UpgradeTags.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v5_2_0/UpgradeTags.java @@ -287,8 +287,7 @@ protected long copyEntry(long groupId, long entryId) throws Exception { ps = con.prepareStatement( "select * from TagsEntry where entryId = ?", - ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ps.setLong(1, entryId); @@ -338,8 +337,7 @@ protected void copyProperties(long entryId, long newEntryId) ps = con.prepareStatement( "select * from TagsProperty where entryId = ?", - ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ps.setLong(1, entryId); @@ -551,8 +549,7 @@ protected void updateGroupIds() throws Exception { "select TA.assetId, TA.groupId, TA_TE.entryId from " + "TagsAssets_TagsEntries TA_TE inner join TagsAsset TA on " + "TA.assetId = TA_TE.assetId", - ResultSet.TYPE_SCROLL_INSENSITIVE, - ResultSet.CONCUR_READ_ONLY); + ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); rs = ps.executeQuery(); diff --git a/portal-impl/src/com/liferay/portal/upgrade/v5_2_3/UpgradeUser.java b/portal-impl/src/com/liferay/portal/upgrade/v5_2_3/UpgradeUser.java index ca8504718effab..ab3d4c1a777756 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v5_2_3/UpgradeUser.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v5_2_3/UpgradeUser.java @@ -36,8 +36,7 @@ protected void doUpgrade() throws Exception { upgradeTable( UserTable.TABLE_NAME, UserTable.TABLE_COLUMNS, - UserTable.TABLE_SQL_CREATE, - UserTable.TABLE_SQL_ADD_INDEXES); + UserTable.TABLE_SQL_CREATE, UserTable.TABLE_SQL_ADD_INDEXES); } StringBundler sb = new StringBundler(9); diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradeAsset.java b/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradeAsset.java index b82bc42fc0a0b8..0c010fc15e6968 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradeAsset.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradeAsset.java @@ -580,8 +580,7 @@ protected void updateResourceCodes() throws Exception { ); updateResourceCodes( - "com.liferay.portlet.tags.model.TagsEntry", - AssetTag.class.getName() + "com.liferay.portlet.tags.model.TagsEntry", AssetTag.class.getName() ); updateResourceCodes( diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradePolls.java b/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradePolls.java index 406d331a07cb36..2a4ab78e97992a 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradePolls.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradePolls.java @@ -44,8 +44,7 @@ protected void doUpgrade() throws Exception { // PollsQuestion upgradeTable( - PollsQuestionTable.TABLE_NAME, - PollsQuestionTable.TABLE_COLUMNS, + PollsQuestionTable.TABLE_NAME, PollsQuestionTable.TABLE_COLUMNS, PollsQuestionTable.TABLE_SQL_CREATE, PollsQuestionTable.TABLE_SQL_ADD_INDEXES); } diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradePortletId.java b/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradePortletId.java index 30f6b60a2a5f0e..b37a335fc5742c 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradePortletId.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_0_0/UpgradePortletId.java @@ -24,56 +24,43 @@ public class UpgradePortletId protected String[][] getPortletIdsArray() { return new String[][] { new String[] { - "7", - "1_WAR_biblegatewayportlet" + "7", "1_WAR_biblegatewayportlet" }, new String[] { - "21", - "1_WAR_randombibleverseportlet" + "21", "1_WAR_randombibleverseportlet" }, new String[] { - "46", - "1_WAR_gospelforasiaportlet" + "46", "1_WAR_gospelforasiaportlet" }, new String[] { - "1_WAR_wolportlet", - "1_WAR_socialnetworkingportlet" + "1_WAR_wolportlet", "1_WAR_socialnetworkingportlet" }, new String[] { - "2_WAR_wolportlet", - "1_WAR_socialcodingportlet" + "2_WAR_wolportlet", "1_WAR_socialcodingportlet" }, new String[] { - "3_WAR_wolportlet", - "2_WAR_socialcodingportlet" + "3_WAR_wolportlet", "2_WAR_socialcodingportlet" }, new String[] { - "4_WAR_wolportlet", - "2_WAR_socialnetworkingportlet" + "4_WAR_wolportlet", "2_WAR_socialnetworkingportlet" }, new String[] { - "5_WAR_wolportlet", - "3_WAR_socialnetworkingportlet" + "5_WAR_wolportlet", "3_WAR_socialnetworkingportlet" }, new String[] { - "6_WAR_wolportlet", - "4_WAR_socialnetworkingportlet" + "6_WAR_wolportlet", "4_WAR_socialnetworkingportlet" }, new String[] { - "7_WAR_wolportlet", - "5_WAR_socialnetworkingportlet" + "7_WAR_wolportlet", "5_WAR_socialnetworkingportlet" }, new String[] { - "8_WAR_wolportlet", - "6_WAR_socialnetworkingportlet" + "8_WAR_wolportlet", "6_WAR_socialnetworkingportlet" }, new String[] { - "9_WAR_wolportlet", - "7_WAR_socialnetworkingportlet" + "9_WAR_wolportlet", "7_WAR_socialnetworkingportlet" }, new String[] { - "10_WAR_wolportlet", - "8_WAR_socialnetworkingportlet" + "10_WAR_wolportlet", "8_WAR_socialnetworkingportlet" } }; } diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_0_1/UpgradeDocumentLibrary.java b/portal-impl/src/com/liferay/portal/upgrade/v6_0_1/UpgradeDocumentLibrary.java index b7820a78c4aab1..229eefc5c8331c 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_0_1/UpgradeDocumentLibrary.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_0_1/UpgradeDocumentLibrary.java @@ -44,8 +44,7 @@ protected void doUpgrade() throws Exception { // DLFileVersion upgradeTable( - DLFileVersionTable.TABLE_NAME, - DLFileVersionTable.TABLE_COLUMNS, + DLFileVersionTable.TABLE_NAME, DLFileVersionTable.TABLE_COLUMNS, DLFileVersionTable.TABLE_SQL_CREATE, DLFileVersionTable.TABLE_SQL_ADD_INDEXES); } diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_0_12_to_6_1_0/UpgradePermission.java b/portal-impl/src/com/liferay/portal/upgrade/v6_0_12_to_6_1_0/UpgradePermission.java index e2da4071659790..b15f7e787f7d92 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_0_12_to_6_1_0/UpgradePermission.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_0_12_to_6_1_0/UpgradePermission.java @@ -171,8 +171,7 @@ protected void doUpgrade() throws Exception { } private static final int[] _SCOPES = { - ResourceConstants.SCOPE_COMPANY, - ResourceConstants.SCOPE_GROUP, + ResourceConstants.SCOPE_COMPANY, ResourceConstants.SCOPE_GROUP, ResourceConstants.SCOPE_GROUP_TEMPLATE }; diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_0_2/UpgradeExpando.java b/portal-impl/src/com/liferay/portal/upgrade/v6_0_2/UpgradeExpando.java index f559787b5a00a8..c78856db05f31c 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_0_2/UpgradeExpando.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_0_2/UpgradeExpando.java @@ -95,8 +95,8 @@ protected void addValue( @Override protected void doUpgrade() throws Exception { updateTables( - JournalArticle.class.getName(), - JournalArticleImpl.TABLE_NAME, "id_"); + JournalArticle.class.getName(), JournalArticleImpl.TABLE_NAME, + "id_"); updateTables( WikiPage.class.getName(), WikiPageImpl.TABLE_NAME, "pageId"); diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeCommunityProperties.java b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeCommunityProperties.java index b86c7205dd381e..a75956d4e32608 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeCommunityProperties.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeCommunityProperties.java @@ -59,8 +59,7 @@ protected void updatePreferences( private static final String[] _NEW_PORTAL_PREFERENCES = { PropsKeys.COMPANY_SECURITY_SITE_LOGO, - PropsKeys.SITES_EMAIL_FROM_ADDRESS, - PropsKeys.SITES_EMAIL_FROM_NAME, + PropsKeys.SITES_EMAIL_FROM_ADDRESS, PropsKeys.SITES_EMAIL_FROM_NAME, PropsKeys.SITES_EMAIL_MEMBERSHIP_REPLY_BODY, PropsKeys.SITES_EMAIL_MEMBERSHIP_REPLY_SUBJECT, PropsKeys.SITES_EMAIL_MEMBERSHIP_REQUEST_BODY, diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeDocumentLibrary.java b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeDocumentLibrary.java index dbc5344a4cc439..a489ced4706f56 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeDocumentLibrary.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeDocumentLibrary.java @@ -296,8 +296,7 @@ protected void updateFileVersions() throws Exception { } catch (SQLException sqle) { upgradeTable( - DLFileVersionTable.TABLE_NAME, - DLFileVersionTable.TABLE_COLUMNS, + DLFileVersionTable.TABLE_NAME, DLFileVersionTable.TABLE_COLUMNS, DLFileVersionTable.TABLE_SQL_CREATE, DLFileVersionTable.TABLE_SQL_ADD_INDEXES); } diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeGroup.java b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeGroup.java index d84a6d6e7ed723..a32bd8b16f05d0 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeGroup.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeGroup.java @@ -40,8 +40,7 @@ protected void doUpgrade() throws Exception { catch (SQLException sqle) { upgradeTable( GroupTable.TABLE_NAME, GroupTable.TABLE_COLUMNS, - GroupTable.TABLE_SQL_CREATE, - GroupTable.TABLE_SQL_ADD_INDEXES); + GroupTable.TABLE_SQL_CREATE, GroupTable.TABLE_SQL_ADD_INDEXES); } updateName(); diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeLock.java b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeLock.java index 17756cdcf4ed2f..838118f35d661c 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeLock.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeLock.java @@ -32,8 +32,7 @@ protected void doUpgrade() throws Exception { catch (SQLException sqle) { upgradeTable( LockTable.TABLE_NAME, LockTable.TABLE_COLUMNS, - LockTable.TABLE_SQL_CREATE, - LockTable.TABLE_SQL_ADD_INDEXES); + LockTable.TABLE_SQL_CREATE, LockTable.TABLE_SQL_ADD_INDEXES); } } diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradePermission.java b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradePermission.java index eec215d7b4651c..68f7a44705c451 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradePermission.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradePermission.java @@ -248,8 +248,7 @@ protected void updatePermissions_6( } private static final int[] _SCOPES = { - ResourceConstants.SCOPE_COMPANY, - ResourceConstants.SCOPE_GROUP, + ResourceConstants.SCOPE_COMPANY, ResourceConstants.SCOPE_GROUP, ResourceConstants.SCOPE_GROUP_TEMPLATE }; diff --git a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeSocial.java b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeSocial.java index c5c81ef85730b3..80dd5a30bdbb70 100644 --- a/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeSocial.java +++ b/portal-impl/src/com/liferay/portal/upgrade/v6_1_0/UpgradeSocial.java @@ -172,8 +172,8 @@ protected void addActivitySetting( valueJSONObject.put("value", value); addActivitySetting( - increment(), groupId, companyId, classNameId, activityType, - name, valueJSONObject.toString()); + increment(), groupId, companyId, classNameId, activityType, name, + valueJSONObject.toString()); } protected void addActivitySetting( diff --git a/portal-impl/src/com/liferay/portal/util/CookieKeys.java b/portal-impl/src/com/liferay/portal/util/CookieKeys.java index 217853150368a5..1331605dd3c999 100644 --- a/portal-impl/src/com/liferay/portal/util/CookieKeys.java +++ b/portal-impl/src/com/liferay/portal/util/CookieKeys.java @@ -46,8 +46,8 @@ public static void addCookie( } public static void addCookie( - HttpServletRequest request, HttpServletResponse response, - Cookie cookie, boolean secure) { + HttpServletRequest request, HttpServletResponse response, Cookie cookie, + boolean secure) { if (!PropsValues.SESSION_ENABLE_PERSISTENT_COOKIES || PropsValues.TCK_URL) { diff --git a/portal-impl/src/com/liferay/portal/util/DiffImpl.java b/portal-impl/src/com/liferay/portal/util/DiffImpl.java index 70d381f2578792..03df7970b417b2 100644 --- a/portal-impl/src/com/liferay/portal/util/DiffImpl.java +++ b/portal-impl/src/com/liferay/portal/util/DiffImpl.java @@ -96,9 +96,8 @@ public List[] diff( // Lines were deleted from source only. _highlightLines( - sourceStringList, deletedMarkerStart, - deletedMarkerEnd, difference.getDeletedStart(), - difference.getDeletedEnd()); + sourceStringList, deletedMarkerStart, deletedMarkerEnd, + difference.getDeletedStart(), difference.getDeletedEnd()); margin = _calculateMargin( sourceResults, targetResults, difference.getDeletedStart(), @@ -490,9 +489,8 @@ private static boolean _lineDiff( // Chars were deleted from source only. _highlightChars( - sourceList, deletedMarkerStart, - deletedMarkerEnd, difference.getDeletedStart(), - difference.getDeletedEnd()); + sourceList, deletedMarkerStart, deletedMarkerEnd, + difference.getDeletedStart(), difference.getDeletedEnd()); sourceChanged = true; } @@ -511,9 +509,8 @@ else if (difference.getDeletedEnd() == Difference.NONE) { // Chars were both deleted and added. _highlightChars( - sourceList, deletedMarkerStart, - deletedMarkerEnd, difference.getDeletedStart(), - difference.getDeletedEnd()); + sourceList, deletedMarkerStart, deletedMarkerEnd, + difference.getDeletedStart(), difference.getDeletedEnd()); sourceChanged = true; diff --git a/portal-impl/src/com/liferay/portal/util/EntityResolver.java b/portal-impl/src/com/liferay/portal/util/EntityResolver.java index 9ff8d4d5b8788f..498c0cff2ac177 100644 --- a/portal-impl/src/com/liferay/portal/util/EntityResolver.java +++ b/portal-impl/src/com/liferay/portal/util/EntityResolver.java @@ -108,8 +108,7 @@ else if (systemId != null) { private static final KeyValuePair[] _PUBLIC_IDS = { new KeyValuePair( - "datatypes", - "datatypes.dtd" + "datatypes", "datatypes.dtd" ), new KeyValuePair( @@ -123,48 +122,39 @@ else if (systemId != null) { ), new KeyValuePair( - "-//Liferay//DTD Display 2.0.0//EN", - "liferay-display_2_0_0.dtd" + "-//Liferay//DTD Display 2.0.0//EN", "liferay-display_2_0_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Display 3.5.0//EN", - "liferay-display_3_5_0.dtd" + "-//Liferay//DTD Display 3.5.0//EN", "liferay-display_3_5_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Display 4.0.0//EN", - "liferay-display_4_0_0.dtd" + "-//Liferay//DTD Display 4.0.0//EN", "liferay-display_4_0_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Display 5.0.0//EN", - "liferay-display_5_0_0.dtd" + "-//Liferay//DTD Display 5.0.0//EN", "liferay-display_5_0_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Display 5.1.0//EN", - "liferay-display_5_1_0.dtd" + "-//Liferay//DTD Display 5.1.0//EN", "liferay-display_5_1_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Display 5.2.0//EN", - "liferay-display_5_2_0.dtd" + "-//Liferay//DTD Display 5.2.0//EN", "liferay-display_5_2_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Display 6.0.0//EN", - "liferay-display_6_0_0.dtd" + "-//Liferay//DTD Display 6.0.0//EN", "liferay-display_6_0_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Display 6.1.0//EN", - "liferay-display_6_1_0.dtd" + "-//Liferay//DTD Display 6.1.0//EN", "liferay-display_6_1_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Display 6.2.0//EN", - "liferay-display_6_2_0.dtd" + "-//Liferay//DTD Display 6.2.0//EN", "liferay-display_6_2_0.dtd" ), new KeyValuePair( @@ -183,28 +173,23 @@ else if (systemId != null) { ), new KeyValuePair( - "-//Liferay//DTD Hook 5.1.0//EN", - "liferay-hook_5_1_0.dtd" + "-//Liferay//DTD Hook 5.1.0//EN", "liferay-hook_5_1_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Hook 5.2.0//EN", - "liferay-hook_5_2_0.dtd" + "-//Liferay//DTD Hook 5.2.0//EN", "liferay-hook_5_2_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Hook 6.0.0//EN", - "liferay-hook_6_0_0.dtd" + "-//Liferay//DTD Hook 6.0.0//EN", "liferay-hook_6_0_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Hook 6.1.0//EN", - "liferay-hook_6_1_0.dtd" + "-//Liferay//DTD Hook 6.1.0//EN", "liferay-hook_6_1_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Hook 6.2.0//EN", - "liferay-hook_6_2_0.dtd" + "-//Liferay//DTD Hook 6.2.0//EN", "liferay-hook_6_2_0.dtd" ), new KeyValuePair( @@ -528,13 +513,11 @@ else if (systemId != null) { ), new KeyValuePair( - "-//Liferay//DTD Social 6.1.0//EN", - "liferay-social_6_1_0.dtd" + "-//Liferay//DTD Social 6.1.0//EN", "liferay-social_6_1_0.dtd" ), new KeyValuePair( - "-//Liferay//DTD Social 6.2.0//EN", - "liferay-social_6_2_0.dtd" + "-//Liferay//DTD Social 6.2.0//EN", "liferay-social_6_2_0.dtd" ), new KeyValuePair( @@ -578,8 +561,7 @@ else if (systemId != null) { ), new KeyValuePair( - "-//SPRING//DTD BEAN//EN", - "spring-beans.dtd" + "-//SPRING//DTD BEAN//EN", "spring-beans.dtd" ), new KeyValuePair( @@ -608,15 +590,13 @@ else if (systemId != null) { ), new KeyValuePair( - "-//W3C//DTD XMLSCHEMA 200102//EN", - "XMLSchema.dtd" + "-//W3C//DTD XMLSCHEMA 200102//EN", "XMLSchema.dtd" ) }; private static final KeyValuePair[] _SYSTEM_IDS = { new KeyValuePair( - "http://java.sun.com/xml/ns/j2ee/j2ee_1_4.xsd", - "j2ee_1_4.xsd" + "http://java.sun.com/xml/ns/j2ee/j2ee_1_4.xsd", "j2ee_1_4.xsd" ), new KeyValuePair( @@ -626,13 +606,11 @@ else if (systemId != null) { ), new KeyValuePair( - "http://java.sun.com/xml/ns/javaee/javaee_5.xsd", - "javaee_5.xsd" + "http://java.sun.com/xml/ns/javaee/javaee_5.xsd", "javaee_5.xsd" ), new KeyValuePair( - "http://java.sun.com/xml/ns/javaee/javaee_6.xsd", - "javaee_6.xsd" + "http://java.sun.com/xml/ns/javaee/javaee_6.xsd", "javaee_6.xsd" ), new KeyValuePair( @@ -648,18 +626,15 @@ else if (systemId != null) { ), new KeyValuePair( - "http://java.sun.com/xml/ns/j2ee/jsp_2_0.xsd", - "jsp_2_0.xsd" + "http://java.sun.com/xml/ns/j2ee/jsp_2_0.xsd", "jsp_2_0.xsd" ), new KeyValuePair( - "http://java.sun.com/xml/ns/javaee/jsp_2_1.xsd", - "jsp_2_1.xsd" + "http://java.sun.com/xml/ns/javaee/jsp_2_1.xsd", "jsp_2_1.xsd" ), new KeyValuePair( - "http://java.sun.com/xml/ns/javaee/jsp_2_2.xsd", - "jsp_2_2.xsd" + "http://java.sun.com/xml/ns/javaee/jsp_2_2.xsd", "jsp_2_2.xsd" ), new KeyValuePair( @@ -673,8 +648,7 @@ else if (systemId != null) { ), new KeyValuePair( - "http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd", - "web-app_2_4.xsd" + "http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd", "web-app_2_4.xsd" ), new KeyValuePair( @@ -718,8 +692,7 @@ else if (systemId != null) { ), new KeyValuePair( - "http://www.w3.org/2001/xml.xsd", - "xml.xsd" + "http://www.w3.org/2001/xml.xsd", "xml.xsd" ) }; diff --git a/portal-impl/src/com/liferay/portal/util/FileMultiValueMap.java b/portal-impl/src/com/liferay/portal/util/FileMultiValueMap.java index 4fc8df43dd21d0..09560a5007df70 100644 --- a/portal-impl/src/com/liferay/portal/util/FileMultiValueMap.java +++ b/portal-impl/src/com/liferay/portal/util/FileMultiValueMap.java @@ -302,10 +302,8 @@ private void _createDatabase() { private void _deleteDatabase() throws Throwable { File[] files = new File[] { new File(_fileName + ".properties"), - new File(_fileName + ".script"), - new File(_fileName + ".log"), - new File(_fileName + ".data"), - new File(_fileName + ".backup") + new File(_fileName + ".script"), new File(_fileName + ".log"), + new File(_fileName + ".data"), new File(_fileName + ".backup") }; for (File file : files) { diff --git a/portal-impl/src/com/liferay/portal/util/HttpImpl.java b/portal-impl/src/com/liferay/portal/util/HttpImpl.java index 8d5f5b390013be..8837df6765f279 100644 --- a/portal-impl/src/com/liferay/portal/util/HttpImpl.java +++ b/portal-impl/src/com/liferay/portal/util/HttpImpl.java @@ -1227,8 +1227,7 @@ else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) { 2); private static final int _MAX_TOTAL_CONNECTIONS = GetterUtil.getInteger( - PropsUtil.get(HttpImpl.class.getName() + ".max.total.connections"), - 20); + PropsUtil.get(HttpImpl.class.getName() + ".max.total.connections"), 20); private static final String _NON_PROXY_HOSTS = SystemProperties.get( "http.nonProxyHosts"); diff --git a/portal-impl/src/com/liferay/portal/util/PortalImpl.java b/portal-impl/src/com/liferay/portal/util/PortalImpl.java index 0490d2faf6da7a..a4082ed87425d6 100644 --- a/portal-impl/src/com/liferay/portal/util/PortalImpl.java +++ b/portal-impl/src/com/liferay/portal/util/PortalImpl.java @@ -1,6152 +1,6140 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portal.util; - -import com.liferay.portal.NoSuchCompanyException; -import com.liferay.portal.NoSuchImageException; -import com.liferay.portal.NoSuchLayoutException; -import com.liferay.portal.NoSuchResourceException; -import com.liferay.portal.NoSuchUserException; -import com.liferay.portal.cluster.ClusterInvokeThreadLocal; -import com.liferay.portal.kernel.bean.BeanPropertiesUtil; -import com.liferay.portal.kernel.cluster.ClusterExecutorUtil; -import com.liferay.portal.kernel.cluster.ClusterRequest; -import com.liferay.portal.kernel.dao.db.DB; -import com.liferay.portal.kernel.dao.db.DBFactoryUtil; -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter; -import com.liferay.portal.kernel.language.LanguageUtil; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.portlet.FriendlyURLMapper; -import com.liferay.portal.kernel.portlet.FriendlyURLMapperThreadLocal; -import com.liferay.portal.kernel.portlet.LiferayPortletMode; -import com.liferay.portal.kernel.portlet.LiferayPortletRequest; -import com.liferay.portal.kernel.portlet.LiferayPortletResponse; -import com.liferay.portal.kernel.portlet.LiferayWindowState; -import com.liferay.portal.kernel.portlet.PortletBag; -import com.liferay.portal.kernel.portlet.PortletBagPool; -import com.liferay.portal.kernel.servlet.BrowserSnifferUtil; -import com.liferay.portal.kernel.servlet.FileTimestampUtil; -import com.liferay.portal.kernel.servlet.HttpHeaders; -import com.liferay.portal.kernel.servlet.HttpMethods; -import com.liferay.portal.kernel.servlet.PipingServletResponse; -import com.liferay.portal.kernel.servlet.SessionErrors; -import com.liferay.portal.kernel.servlet.StringServletResponse; -import com.liferay.portal.kernel.servlet.taglib.ui.BreadcrumbEntry; -import com.liferay.portal.kernel.upload.UploadPortletRequest; -import com.liferay.portal.kernel.upload.UploadServletRequest; -import com.liferay.portal.kernel.util.ArrayUtil; -import com.liferay.portal.kernel.util.Base64; -import com.liferay.portal.kernel.util.CalendarFactoryUtil; -import com.liferay.portal.kernel.util.CharPool; -import com.liferay.portal.kernel.util.ContentTypes; -import com.liferay.portal.kernel.util.ContextPathUtil; -import com.liferay.portal.kernel.util.DeterminateKeyGenerator; -import com.liferay.portal.kernel.util.GetterUtil; -import com.liferay.portal.kernel.util.HtmlUtil; -import com.liferay.portal.kernel.util.Http; -import com.liferay.portal.kernel.util.HttpUtil; -import com.liferay.portal.kernel.util.InheritableMap; -import com.liferay.portal.kernel.util.JavaConstants; -import com.liferay.portal.kernel.util.ListUtil; -import com.liferay.portal.kernel.util.LocaleUtil; -import com.liferay.portal.kernel.util.MethodHandler; -import com.liferay.portal.kernel.util.MethodKey; -import com.liferay.portal.kernel.util.ParamUtil; -import com.liferay.portal.kernel.util.PropsKeys; -import com.liferay.portal.kernel.util.ReleaseInfo; -import com.liferay.portal.kernel.util.SetUtil; -import com.liferay.portal.kernel.util.StringBundler; -import com.liferay.portal.kernel.util.StringComparator; -import com.liferay.portal.kernel.util.StringPool; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.kernel.util.Time; -import com.liferay.portal.kernel.util.UnicodeProperties; -import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.kernel.xml.QName; -import com.liferay.portal.model.BaseModel; -import com.liferay.portal.model.ClassName; -import com.liferay.portal.model.ColorScheme; -import com.liferay.portal.model.Company; -import com.liferay.portal.model.Group; -import com.liferay.portal.model.GroupConstants; -import com.liferay.portal.model.Layout; -import com.liferay.portal.model.LayoutConstants; -import com.liferay.portal.model.LayoutSet; -import com.liferay.portal.model.LayoutType; -import com.liferay.portal.model.LayoutTypePortlet; -import com.liferay.portal.model.LayoutTypePortletConstants; -import com.liferay.portal.model.Organization; -import com.liferay.portal.model.Portlet; -import com.liferay.portal.model.PublicRenderParameter; -import com.liferay.portal.model.Resource; -import com.liferay.portal.model.ResourceCode; -import com.liferay.portal.model.ResourceConstants; -import com.liferay.portal.model.ResourcePermission; -import com.liferay.portal.model.Role; -import com.liferay.portal.model.RoleConstants; -import com.liferay.portal.model.Theme; -import com.liferay.portal.model.Ticket; -import com.liferay.portal.model.TicketConstants; -import com.liferay.portal.model.User; -import com.liferay.portal.model.UserGroup; -import com.liferay.portal.model.VirtualLayoutConstants; -import com.liferay.portal.model.impl.LayoutTypePortletImpl; -import com.liferay.portal.model.impl.VirtualLayout; -import com.liferay.portal.plugin.PluginPackageUtil; -import com.liferay.portal.security.auth.AuthException; -import com.liferay.portal.security.auth.AuthTokenUtil; -import com.liferay.portal.security.auth.CompanyThreadLocal; -import com.liferay.portal.security.auth.PrincipalException; -import com.liferay.portal.security.permission.ActionKeys; -import com.liferay.portal.security.permission.PermissionChecker; -import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; -import com.liferay.portal.security.permission.ResourceActionsUtil; -import com.liferay.portal.service.ClassNameLocalServiceUtil; -import com.liferay.portal.service.CompanyLocalServiceUtil; -import com.liferay.portal.service.GroupLocalServiceUtil; -import com.liferay.portal.service.GroupServiceUtil; -import com.liferay.portal.service.LayoutLocalServiceUtil; -import com.liferay.portal.service.LayoutSetLocalServiceUtil; -import com.liferay.portal.service.PortletLocalServiceUtil; -import com.liferay.portal.service.ResourceCodeLocalServiceUtil; -import com.liferay.portal.service.ResourceLocalServiceUtil; -import com.liferay.portal.service.ResourcePermissionLocalServiceUtil; -import com.liferay.portal.service.TicketLocalServiceUtil; -import com.liferay.portal.service.UserLocalServiceUtil; -import com.liferay.portal.service.UserServiceUtil; -import com.liferay.portal.service.permission.GroupPermissionUtil; -import com.liferay.portal.service.permission.LayoutPermissionUtil; -import com.liferay.portal.service.permission.LayoutPrototypePermissionUtil; -import com.liferay.portal.service.permission.LayoutSetPrototypePermissionUtil; -import com.liferay.portal.service.permission.OrganizationPermissionUtil; -import com.liferay.portal.service.permission.PortletPermissionUtil; -import com.liferay.portal.service.permission.UserPermissionUtil; -import com.liferay.portal.servlet.filters.i18n.I18nFilter; -import com.liferay.portal.servlet.filters.secure.NonceUtil; -import com.liferay.portal.struts.StrutsUtil; -import com.liferay.portal.theme.ThemeDisplay; -import com.liferay.portal.upload.UploadPortletRequestImpl; -import com.liferay.portal.upload.UploadServletRequestImpl; -import com.liferay.portal.util.comparator.PortletControlPanelWeightComparator; -import com.liferay.portal.webserver.WebServerServlet; -import com.liferay.portlet.ActionResponseImpl; -import com.liferay.portlet.ControlPanelEntry; -import com.liferay.portlet.DefaultControlPanelEntryFactory; -import com.liferay.portlet.PortletConfigFactoryUtil; -import com.liferay.portlet.PortletConfigImpl; -import com.liferay.portlet.PortletContextImpl; -import com.liferay.portlet.PortletPreferencesFactoryUtil; -import com.liferay.portlet.PortletPreferencesImpl; -import com.liferay.portlet.PortletPreferencesThreadLocal; -import com.liferay.portlet.PortletPreferencesWrapper; -import com.liferay.portlet.PortletQNameUtil; -import com.liferay.portlet.PortletRequestImpl; -import com.liferay.portlet.PortletResponseImpl; -import com.liferay.portlet.PortletURLFactoryUtil; -import com.liferay.portlet.PortletURLImpl; -import com.liferay.portlet.RenderRequestImpl; -import com.liferay.portlet.RenderResponseImpl; -import com.liferay.portlet.StateAwareResponseImpl; -import com.liferay.portlet.UserAttributes; -import com.liferay.portlet.admin.util.OmniadminUtil; -import com.liferay.portlet.asset.model.AssetTag; -import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil; -import com.liferay.portlet.blogs.model.BlogsEntry; -import com.liferay.portlet.bookmarks.model.BookmarksEntry; -import com.liferay.portlet.calendar.model.CalEvent; -import com.liferay.portlet.documentlibrary.model.DLFileEntry; -import com.liferay.portlet.expando.ValueDataException; -import com.liferay.portlet.expando.model.ExpandoBridge; -import com.liferay.portlet.expando.model.ExpandoColumnConstants; -import com.liferay.portlet.journal.asset.JournalArticleAssetRendererFactory; -import com.liferay.portlet.journal.model.JournalArticle; -import com.liferay.portlet.journal.model.JournalArticleConstants; -import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil; -import com.liferay.portlet.login.util.LoginUtil; -import com.liferay.portlet.messageboards.model.MBMessage; -import com.liferay.portlet.messageboards.model.MBThread; -import com.liferay.portlet.social.model.SocialRelationConstants; -import com.liferay.portlet.social.util.FacebookUtil; -import com.liferay.portlet.wiki.model.WikiPage; -import com.liferay.util.Encryptor; -import com.liferay.util.JS; -import com.liferay.util.PwdGenerator; -import com.liferay.util.UniqueList; -import com.liferay.util.servlet.DynamicServletRequest; - -import java.io.IOException; -import java.io.Serializable; - -import java.lang.reflect.Method; - -import java.net.InetAddress; -import java.net.UnknownHostException; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Calendar; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.ResourceBundle; -import java.util.Set; -import java.util.TimeZone; -import java.util.TreeSet; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.PortletConfig; -import javax.portlet.PortletMode; -import javax.portlet.PortletPreferences; -import javax.portlet.PortletRequest; -import javax.portlet.PortletResponse; -import javax.portlet.PortletURL; -import javax.portlet.PreferencesValidator; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.portlet.ValidatorException; -import javax.portlet.WindowState; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import javax.servlet.jsp.PageContext; - -import org.apache.struts.Globals; - -/** - * @author Brian Wing Shun Chan - * @author Brian Myunghun Kim - * @author Jorge Ferrer - * @author Raymond Augé - * @author Eduardo Lundgren - * @author Wesley Gong - * @author Hugo Huijser - * @author Juan Fernández - */ -public class PortalImpl implements Portal { - - public PortalImpl() { - - // Computer name - - _computerName = System.getProperty("env.COMPUTERNAME"); - - if (Validator.isNull(_computerName)) { - _computerName = System.getProperty("env.HOST"); - } - - if (Validator.isNull(_computerName)) { - _computerName = System.getProperty("env.HOSTNAME"); - } - - if (Validator.isNull(_computerName)) { - try { - _computerName = InetAddress.getLocalHost().getHostName(); - } - catch (UnknownHostException uhe) { - } - } - - try { - _computerAddress = InetAddress.getByName( - _computerName).getHostAddress(); - } - catch (UnknownHostException uhe) { - } - - if (Validator.isNull(_computerAddress)) { - try { - _computerAddress = InetAddress.getLocalHost().getHostAddress(); - } - catch (UnknownHostException uhe) { - } - } - - // Paths - - _pathProxy = PropsValues.PORTAL_PROXY_PATH; - - _pathContext = ContextPathUtil.getContextPath(PropsValues.PORTAL_CTX); - _pathContext = _pathProxy.concat(_pathContext); - - _pathFriendlyURLPrivateGroup = - _pathContext + _PRIVATE_GROUP_SERVLET_MAPPING; - _pathFriendlyURLPrivateUser = - _pathContext + _PRIVATE_USER_SERVLET_MAPPING; - _pathFriendlyURLPublic = _pathContext + _PUBLIC_GROUP_SERVLET_MAPPING; - _pathImage = _pathContext + PATH_IMAGE; - _pathMain = _pathContext + PATH_MAIN; - - // Groups - - String[] customSystemGroups = PropsUtil.getArray( - PropsKeys.SYSTEM_GROUPS); - - if ((customSystemGroups == null) || (customSystemGroups.length == 0)) { - _allSystemGroups = GroupConstants.SYSTEM_GROUPS; - } - else { - _allSystemGroups = ArrayUtil.append( - GroupConstants.SYSTEM_GROUPS, customSystemGroups); - } - - _sortedSystemGroups = new String[_allSystemGroups.length]; - - System.arraycopy( - _allSystemGroups, 0, _sortedSystemGroups, 0, - _allSystemGroups.length); - - Arrays.sort(_sortedSystemGroups, new StringComparator()); - - // Regular roles - - String[] customSystemRoles = PropsUtil.getArray(PropsKeys.SYSTEM_ROLES); - - if ((customSystemRoles == null) || (customSystemRoles.length == 0)) { - _allSystemRoles = RoleConstants.SYSTEM_ROLES; - } - else { - _allSystemRoles = ArrayUtil.append( - RoleConstants.SYSTEM_ROLES, customSystemRoles); - } - - _sortedSystemRoles = new String[_allSystemRoles.length]; - - System.arraycopy( - _allSystemRoles, 0, _sortedSystemRoles, 0, _allSystemRoles.length); - - Arrays.sort(_sortedSystemRoles, new StringComparator()); - - // Organization roles - - String[] customSystemOrganizationRoles = PropsUtil.getArray( - PropsKeys.SYSTEM_ORGANIZATION_ROLES); - - if ((customSystemOrganizationRoles == null) || - (customSystemOrganizationRoles.length == 0)) { - - _allSystemOrganizationRoles = - RoleConstants.SYSTEM_ORGANIZATION_ROLES; - } - else { - _allSystemOrganizationRoles = ArrayUtil.append( - RoleConstants.SYSTEM_ORGANIZATION_ROLES, - customSystemOrganizationRoles); - } - - _sortedSystemOrganizationRoles = - new String[_allSystemOrganizationRoles.length]; - - System.arraycopy( - _allSystemOrganizationRoles, 0, _sortedSystemOrganizationRoles, 0, - _allSystemOrganizationRoles.length); - - Arrays.sort(_sortedSystemOrganizationRoles, new StringComparator()); - - // Site roles - - String[] customSystemSiteRoles = PropsUtil.getArray( - PropsKeys.SYSTEM_SITE_ROLES); - - if ((customSystemSiteRoles == null) || - (customSystemSiteRoles.length == 0)) { - - _allSystemSiteRoles = RoleConstants.SYSTEM_SITE_ROLES; - } - else { - _allSystemSiteRoles = ArrayUtil.append( - RoleConstants.SYSTEM_SITE_ROLES, customSystemSiteRoles); - } - - _sortedSystemSiteRoles = new String[_allSystemSiteRoles.length]; - - System.arraycopy( - _allSystemSiteRoles, 0, _sortedSystemSiteRoles, 0, - _allSystemSiteRoles.length); - - Arrays.sort(_sortedSystemSiteRoles, new StringComparator()); - - // Authentication token ignore actions and tokens - - _authTokenIgnoreActions = SetUtil.fromArray( - PropsValues.AUTH_TOKEN_IGNORE_ACTIONS); - _authTokenIgnorePortlets = SetUtil.fromArray( - PropsValues.AUTH_TOKEN_IGNORE_PORTLETS); - - // Portlet add default resource check white list - - resetPortletAddDefaultResourceCheckWhitelist(); - resetPortletAddDefaultResourceCheckWhitelistActions(); - - // Reserved parameter names - - _reservedParams = new HashSet(); - - // Portal authentication - - _reservedParams.add("p_auth"); - _reservedParams.add("p_auth_secret"); - - // Portal layout - - _reservedParams.add("p_l_id"); - _reservedParams.add("p_l_reset"); - - // Portal portlet - - _reservedParams.add("p_p_auth"); - _reservedParams.add("p_p_id"); - _reservedParams.add("p_p_i_id"); - _reservedParams.add("p_p_lifecycle"); - _reservedParams.add("p_p_url_type"); - _reservedParams.add("p_p_state"); - _reservedParams.add("p_p_state_rcv"); // LPS-14144 - _reservedParams.add("p_p_mode"); - _reservedParams.add("p_p_resource_id"); - _reservedParams.add("p_p_cacheability"); - _reservedParams.add("p_p_width"); - _reservedParams.add("p_p_col_id"); - _reservedParams.add("p_p_col_pos"); - _reservedParams.add("p_p_col_count"); - _reservedParams.add("p_p_static"); - _reservedParams.add("p_p_isolated"); - - // Portal theme - - _reservedParams.add("p_t_lifecycle"); // LPS-14383 - - // Portal virtual layout - - _reservedParams.add("p_v_l_s_g_id"); // LPS-23010 - - // Portal outer portlet - - _reservedParams.add("p_o_p_id"); // LPS-12097 - - // Portal fragment - - _reservedParams.add("p_f_id"); - - // Portal journal article - - _reservedParams.add("p_j_a_id"); // LPS-16418 - - // Miscellaneous - - _reservedParams.add("saveLastPath"); - _reservedParams.add("scroll"); - } - - public void addPageDescription( - String description, HttpServletRequest request) { - - String requestDescription = (String)request.getAttribute( - WebKeys.PAGE_DESCRIPTION); - - if (requestDescription != null) { - description = requestDescription + StringPool.SPACE + description; - } - - request.setAttribute(WebKeys.PAGE_DESCRIPTION, description); - } - - public void addPageKeywords(String keywords, HttpServletRequest request) { - List requestKeywords = (List)request.getAttribute( - WebKeys.PAGE_KEYWORDS); - - if (requestKeywords == null) { - requestKeywords = new UniqueList(); - } - - String[] keywordsArray = StringUtil.split(keywords); - - for (String keyword : keywordsArray) { - if (!requestKeywords.contains(keyword.toLowerCase())) { - requestKeywords.add(keyword.toLowerCase()); - } - } - - request.setAttribute(WebKeys.PAGE_KEYWORDS, requestKeywords); - } - - public void addPageSubtitle(String subtitle, HttpServletRequest request) { - String requestSubtitle = (String)request.getAttribute( - WebKeys.PAGE_SUBTITLE); - - if (requestSubtitle != null) { - subtitle = requestSubtitle + StringPool.SPACE + subtitle; - } - - request.setAttribute(WebKeys.PAGE_SUBTITLE, subtitle); - } - - public void addPageTitle(String title, HttpServletRequest request) { - String requestTitle = (String)request.getAttribute(WebKeys.PAGE_TITLE); - - if (requestTitle != null) { - title = requestTitle + StringPool.SPACE + title; - } - - request.setAttribute(WebKeys.PAGE_TITLE, title); - } - - public void addPortalPortEventListener( - PortalPortEventListener portalPortEventListener) { - - if (!_portalPortEventListeners.contains(portalPortEventListener)) { - _portalPortEventListeners.add(portalPortEventListener); - } - } - - public void addPortletBreadcrumbEntry( - HttpServletRequest request, String title, String url) { - - addPortletBreadcrumbEntry(request, title, url, null); - } - - public void addPortletBreadcrumbEntry( - HttpServletRequest request, String title, String url, - Map data) { - - List breadcrumbEntries = - (List)request.getAttribute( - WebKeys.PORTLET_BREADCRUMBS); - - if (breadcrumbEntries == null) { - breadcrumbEntries = new ArrayList(); - - request.setAttribute( - WebKeys.PORTLET_BREADCRUMBS, breadcrumbEntries); - } - - BreadcrumbEntry breadcrumbEntry = new BreadcrumbEntry(); - - breadcrumbEntry.setData(data); - breadcrumbEntry.setTitle(title); - breadcrumbEntry.setURL(url); - - breadcrumbEntries.add(breadcrumbEntry); - } - - public void addPortletDefaultResource( - HttpServletRequest request, Portlet portlet) - throws PortalException, SystemException { - - ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( - WebKeys.THEME_DISPLAY); - - Layout layout = themeDisplay.getLayout(); - - addDefaultResource(themeDisplay, layout, portlet, true); - addDefaultResource(themeDisplay, layout, portlet, false); - } - - public void addPortletDefaultResource( - long companyId, Layout layout, Portlet portlet) - throws PortalException, SystemException { - - addDefaultResource(companyId, layout, portlet, true); - addDefaultResource(companyId, layout, portlet, false); - } - - public String addPreservedParameters( - ThemeDisplay themeDisplay, Layout layout, String url, - boolean doAsUser) { - - if (doAsUser) { - if (Validator.isNotNull(themeDisplay.getDoAsUserId())) { - url = HttpUtil.addParameter( - url, "doAsUserId", themeDisplay.getDoAsUserId()); - } - - if (Validator.isNotNull(themeDisplay.getDoAsUserLanguageId())) { - url = HttpUtil.addParameter( - url, "doAsUserLanguageId", - themeDisplay.getDoAsUserLanguageId()); - } - } - - if (layout.isTypeControlPanel()) { - if (themeDisplay.getDoAsGroupId() > 0) { - url = HttpUtil.addParameter( - url, "doAsGroupId", themeDisplay.getDoAsGroupId()); - } - - if (themeDisplay.getRefererPlid() != LayoutConstants.DEFAULT_PLID) { - url = HttpUtil.addParameter( - url, "refererPlid", themeDisplay.getRefererPlid()); - } - - if (Validator.isNotNull(themeDisplay.getControlPanelCategory())) { - url = HttpUtil.addParameter( - url, "controlPanelCategory", - themeDisplay.getControlPanelCategory()); - } - } - - return url; - } - - public String addPreservedParameters( - ThemeDisplay themeDisplay, String url) { - - return addPreservedParameters( - themeDisplay, themeDisplay.getLayout(), url, true); - } - - public void clearRequestParameters(RenderRequest renderRequest) { - RenderRequestImpl renderRequestImpl = (RenderRequestImpl)renderRequest; - - if (renderRequestImpl.isTriggeredByActionURL()) { - Map renderParameters = - renderRequestImpl.getRenderParameters(); - - renderParameters.clear(); - } - } - - public void copyRequestParameters( - ActionRequest actionRequest, ActionResponse actionResponse) { - - if (actionResponse instanceof StateAwareResponseImpl) { - StateAwareResponseImpl stateAwareResponseImpl = - (StateAwareResponseImpl)actionResponse; - - if (stateAwareResponseImpl.getRedirectLocation() != null) { - if (_log.isDebugEnabled()) { - _log.debug( - "Cannot copy parameters on a redirected " + - "StateAwareResponseImpl"); - } - - return; - } - } - - ActionResponseImpl actionResponseImpl = - (ActionResponseImpl)actionResponse; - - Map renderParameters = - actionResponseImpl.getRenderParameterMap(); - - actionResponse.setRenderParameter("p_p_lifecycle", "1"); - - Enumeration enu = actionRequest.getParameterNames(); - - while (enu.hasMoreElements()) { - String param = enu.nextElement(); - String[] values = actionRequest.getParameterValues(param); - - if (renderParameters.get( - actionResponseImpl.getNamespace() + param) == null) { - - actionResponse.setRenderParameter(param, values); - } - } - } - - public String escapeRedirect(String url) { - if (Validator.isNull(url) || !HttpUtil.hasDomain(url)) { - return url; - } - - String domain = HttpUtil.getDomain(url); - - int pos = -1; - - if ((pos = domain.indexOf(CharPool.COLON)) != -1) { - domain = domain.substring(0, pos); - } - - try { - Company company = CompanyLocalServiceUtil.fetchCompanyByVirtualHost( - domain); - - if (company != null) { - return url; - } - } - catch (Exception e) { - } - - try { - LayoutSet layoutSet = LayoutSetLocalServiceUtil.fetchLayoutSet( - domain); - - if (layoutSet != null) { - return url; - } - } - catch (Exception e) { - } - - try { - String securityMode = PropsValues.REDIRECT_URL_SECURITY_MODE; - - if (securityMode.equals("domain")) { - String[] allowedDomains = - PropsValues.REDIRECT_URL_DOMAINS_ALLOWED; - - if ((allowedDomains.length > 0) && - !ArrayUtil.contains(allowedDomains, domain)) { - - if (_log.isDebugEnabled()) { - _log.debug("Redirect URL " + url + " is not allowed"); - } - - url = null; - } - } - else if (securityMode.equals("ip")) { - String[] allowedIps = PropsValues.REDIRECT_URL_IPS_ALLOWED; - - InetAddress inetAddress = InetAddress.getByName(domain); - - if ((allowedIps.length > 0) && - !ArrayUtil.contains( - allowedIps, inetAddress.getHostAddress())) { - - String serverIp = getComputerAddress(); - - if (!serverIp.equals(inetAddress.getHostAddress()) || - !ArrayUtil.contains(allowedIps, "SERVER_IP")) { - - if (_log.isDebugEnabled()) { - _log.debug( - "Redirect URL " + url + " is not allowed"); - } - - url = null; - } - } - } - } - catch (UnknownHostException uhe) { - if (_log.isDebugEnabled()) { - _log.debug("Unable to determine IP for redirect URL " + url); - } - - url = null; - } - - return url; - } - - public String generateRandomKey(HttpServletRequest request, String input) { - ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( - WebKeys.THEME_DISPLAY); - - if (themeDisplay.isLifecycleResource() || - themeDisplay.isStateExclusive()) { - - return PwdGenerator.getPassword(PwdGenerator.KEY3, 4); - } - else { - return DeterminateKeyGenerator.generate(input); - } - } - - public String getActualURL( - long groupId, boolean privateLayout, String mainPath, - String friendlyURL, Map params, - Map requestContext) - throws PortalException, SystemException { - - String actualURL = null; - - if (friendlyURL != null) { - if (friendlyURL.startsWith( - JournalArticleConstants.CANONICAL_URL_SEPARATOR)) { - - try { - actualURL = getJournalArticleActualURL( - groupId, mainPath, friendlyURL, params, requestContext); - } - catch (Exception e) { - friendlyURL = null; - } - } - else if (friendlyURL.startsWith( - VirtualLayoutConstants.CANONICAL_URL_SEPARATOR)) { - - try { - actualURL = getVirtualLayoutActualURL( - groupId, privateLayout, mainPath, friendlyURL, params, - requestContext); - } - catch (Exception e) { - friendlyURL = null; - } - } - } - - if (actualURL == null) { - actualURL = getLayoutActualURL( - groupId, privateLayout, mainPath, friendlyURL, params, - requestContext); - } - - return actualURL; - } - - public Locale[] getAlternateLocales(HttpServletRequest request) - throws SystemException, PortalException { - - Locale[] availableLocales = LanguageUtil.getAvailableLocales(); - - long mainJournalArticleId = ParamUtil.getLong(request, "p_j_a_id"); - - if (mainJournalArticleId > 0) { - JournalArticle mainJournalArticle = - JournalArticleLocalServiceUtil.getJournalArticle( - mainJournalArticleId); - - if (mainJournalArticle != null) { - String[] articleLocales = - mainJournalArticle.getAvailableLocales(); - - if (articleLocales.length > 1) { - Locale[] alternateLocales = new Locale[ - availableLocales.length - articleLocales.length]; - - int i = 0; - - for (Locale locale : availableLocales) { - if (!ArrayUtil.contains( - articleLocales, LocaleUtil.toLanguageId(locale))) { - - alternateLocales[i] = locale; - - i++; - } - } - - return alternateLocales; - } - } - } - - return availableLocales; - } - - public String getAlternateURL( - String canonicalURL, ThemeDisplay themeDisplay, Locale locale) { - - LayoutSet layoutSet = themeDisplay.getLayoutSet(); - - String virtualHost = null; - - if (Validator.isNotNull(layoutSet.getVirtualHostname())) { - virtualHost = layoutSet.getVirtualHostname(); - } - else { - Company company = themeDisplay.getCompany(); - - virtualHost = company.getVirtualHostname(); - } - - String i18nPath = buildI18NPath(locale); - - if (Validator.isNull(virtualHost)) { - return canonicalURL.replaceFirst( - _PUBLIC_GROUP_SERVLET_MAPPING, - i18nPath.concat(_PUBLIC_GROUP_SERVLET_MAPPING)); - } - - // www.liferay.com:8080/page to www.liferay.com:8080/es/page - - int pos = canonicalURL.indexOf(virtualHost); - - if (pos > 0) { - pos += virtualHost.length(); - - pos = canonicalURL.indexOf(CharPool.SLASH, pos); - - if ((pos > 0) && (pos < canonicalURL.length())) { - return canonicalURL.substring(0, pos).concat( - i18nPath).concat(canonicalURL.substring(pos)); - } - } - - return canonicalURL.concat(i18nPath); - } - - public Set getAuthTokenIgnoreActions() { - return _authTokenIgnoreActions; - } - - public Set getAuthTokenIgnorePortlets() { - return _authTokenIgnorePortlets; - } - - public BaseModel getBaseModel(Resource resource) - throws PortalException, SystemException { - - ResourceCode resourceCode = - ResourceCodeLocalServiceUtil.getResourceCode(resource.getCodeId()); - - String modelName = resourceCode.getName(); - String primKey = resource.getPrimKey(); - - return getBaseModel(modelName, primKey); - } - - public BaseModel getBaseModel(ResourcePermission resourcePermission) - throws PortalException, SystemException { - - String modelName = resourcePermission.getName(); - String primKey = resourcePermission.getPrimKey(); - - return getBaseModel(modelName, primKey); - } - - public BaseModel getBaseModel(String modelName, String primKey) - throws PortalException, SystemException { - - if (!modelName.contains(".model.")) { - return null; - } - - String[] parts = StringUtil.split(modelName, CharPool.PERIOD); - - if ((parts.length <= 2) || !parts[parts.length - 2].equals("model")) { - return null; - } - - parts[parts.length - 2] = "service"; - - String serviceName = - StringUtil.merge(parts, StringPool.PERIOD) + "LocalServiceUtil"; - String methodName = "get" + parts[parts.length - 1]; - - Method method = null; - - try { - Class serviceUtil = Class.forName(serviceName); - - if (Validator.isNumber(primKey)) { - method = serviceUtil.getMethod( - methodName, new Class[] {Long.TYPE}); - - return (BaseModel)method.invoke(null, new Long(primKey)); - } - else { - method = serviceUtil.getMethod( - methodName, new Class[] {String.class}); - - return (BaseModel)method.invoke(null, primKey); - } - } - catch (Exception e) { - Throwable cause = e.getCause(); - - if (cause instanceof PortalException) { - throw (PortalException)cause; - } - else if (cause instanceof SystemException) { - throw (SystemException)cause; - } - else { - throw new SystemException(cause); - } - } - } - - public long getBasicAuthUserId(HttpServletRequest request) - throws PortalException, SystemException { - - long companyId = PortalInstances.getCompanyId(request); - - return getBasicAuthUserId(request, companyId); - } - - public long getBasicAuthUserId(HttpServletRequest request, long companyId) - throws PortalException, SystemException { - - long userId = 0; - - String authorizationHeader = request.getHeader( - HttpHeaders.AUTHORIZATION); - - if (Validator.isNull(authorizationHeader)) { - return userId; - } - - String[] authorizationArray = authorizationHeader.split("\\s+"); - - String authorization = authorizationArray[0]; - String credentials = new String(Base64.decode(authorizationArray[1])); - - if (!authorization.equalsIgnoreCase(HttpServletRequest.BASIC_AUTH)) { - return userId; - } - - String[] loginAndPassword = StringUtil.split( - credentials, CharPool.COLON); - - String login = loginAndPassword[0].trim(); - - String password = null; - - if (loginAndPassword.length > 1) { - password = loginAndPassword[1].trim(); - } - - // Strip @uid and @sn for backwards compatibility - - if (login.endsWith("@uid")) { - int pos = login.indexOf("@uid"); - - login = login.substring(0, pos); - } - else if (login.endsWith("@sn")) { - int pos = login.indexOf("@sn"); - - login = login.substring(0, pos); - } - - try { - userId = LoginUtil.getAuthenticatedUserId( - request, login, password, null); - } - catch (AuthException ae) { - } - - return userId; - } - - public String getCanonicalURL( - String completeURL, ThemeDisplay themeDisplay, Layout layout) - throws PortalException, SystemException { - - completeURL = removeRedirectParameter(completeURL); - - String parametersURL = StringPool.BLANK; - - int pos = completeURL.indexOf(Portal.FRIENDLY_URL_SEPARATOR); - - if (pos == -1) { - pos = completeURL.indexOf(StringPool.QUESTION); - } - - String groupFriendlyURL = completeURL; - - if (pos != -1) { - groupFriendlyURL = completeURL.substring(0, pos); - - parametersURL = completeURL.substring(pos); - } - - if (layout == null) { - layout = themeDisplay.getLayout(); - } - - String layoutFriendlyURL = StringPool.BLANK; - - if ((groupFriendlyURL.contains(layout.getFriendlyURL()) || - groupFriendlyURL.contains( - StringPool.SLASH + layout.getLayoutId())) && - (!layout.isFirstParent() || Validator.isNotNull(parametersURL))) { - - layoutFriendlyURL = layout.getFriendlyURL(); - } - - Group group = layout.getGroup(); - - groupFriendlyURL = getGroupFriendlyURL( - group, layout.isPrivateLayout(), themeDisplay, true); - - return groupFriendlyURL.concat(layoutFriendlyURL).concat(parametersURL); - } - - /** - * @deprecated {@link #getCDNHost(boolean)} - */ - public String getCDNHost() { - long companyId = CompanyThreadLocal.getCompanyId(); - - return getCDNHostHttp(companyId); - } - - public String getCDNHost(boolean secure) { - long companyId = CompanyThreadLocal.getCompanyId(); - - if (secure) { - return getCDNHostHttps(companyId); - } - else { - return getCDNHostHttp(companyId); - } - } - - public String getCDNHost(HttpServletRequest request) - throws PortalException, SystemException { - - String cdnHost = null; - - Company company = getCompany(request); - - if (request.isSecure()) { - cdnHost = getCDNHostHttps(company.getCompanyId()); - } - else { - cdnHost = getCDNHostHttp(company.getCompanyId()); - } - - return ParamUtil.getString(request, "cdn_host", cdnHost); - } - - public String getCDNHostHttp(long companyId) { - String cdnHostHttp = _cdnHostHttpMap.get(companyId); - - if (cdnHostHttp != null) { - return cdnHostHttp; - } - - try { - cdnHostHttp = PrefsPropsUtil.getString( - companyId, PropsKeys.CDN_HOST_HTTP, PropsValues.CDN_HOST_HTTP); - } - catch (Exception e) { - } - - if ((cdnHostHttp == null) || cdnHostHttp.startsWith("${")) { - cdnHostHttp = StringPool.BLANK; - } - - _cdnHostHttpMap.put(companyId, cdnHostHttp); - - return cdnHostHttp; - } - - public String getCDNHostHttps(long companyId) { - String cdnHostHttps = _cdnHostHttpsMap.get(companyId); - - if (cdnHostHttps != null) { - return cdnHostHttps; - } - - try { - cdnHostHttps = PrefsPropsUtil.getString( - companyId, PropsKeys.CDN_HOST_HTTPS, - PropsValues.CDN_HOST_HTTPS); - } - catch (SystemException e) { - } - - if ((cdnHostHttps == null) || cdnHostHttps.startsWith("${")) { - cdnHostHttps = StringPool.BLANK; - } - - _cdnHostHttpsMap.put(companyId, cdnHostHttps); - - return cdnHostHttps; - } - - public String getClassName(long classNameId) { - try { - ClassName className = ClassNameLocalServiceUtil.getClassName( - classNameId); - - return className.getValue(); - } - catch (Exception e) { - throw new RuntimeException( - "Unable to get class name from id " + classNameId); - } - } - - public long getClassNameId(Class clazz) { - return ClassNameLocalServiceUtil.getClassNameId(clazz); - } - - public long getClassNameId(String value) { - return ClassNameLocalServiceUtil.getClassNameId(value); - } - - public String getClassNamePortletId(String className) { - String portletId = StringPool.BLANK; - - if (className.startsWith("com.liferay.portlet.blogs")) { - portletId = PortletKeys.BLOGS; - } - else if (className.startsWith("com.liferay.portlet.bookmarks")) { - portletId = PortletKeys.BOOKMARKS; - } - else if (className.startsWith("com.liferay.portlet.calendar")) { - portletId = PortletKeys.CALENDAR; - } - else if (className.startsWith("com.liferay.portlet.documentlibrary")) { - portletId = PortletKeys.DOCUMENT_LIBRARY; - } - else if (className.startsWith("com.liferay.portlet.imagegallery")) { - portletId = PortletKeys.MEDIA_GALLERY_DISPLAY; - } - else if (className.startsWith("com.liferay.portlet.journal")) { - portletId = PortletKeys.JOURNAL; - } - else if (className.startsWith("com.liferay.portlet.messageboards")) { - portletId = PortletKeys.MESSAGE_BOARDS; - } - else if (className.startsWith("com.liferay.portlet.wiki")) { - portletId = PortletKeys.WIKI; - } - - return portletId; - } - - public Company getCompany(HttpServletRequest request) - throws PortalException, SystemException { - - long companyId = getCompanyId(request); - - if (companyId <= 0) { - return null; - } - - Company company = (Company)request.getAttribute(WebKeys.COMPANY); - - if (company == null) { - - // LEP-5994 - - try { - company = CompanyLocalServiceUtil.getCompanyById(companyId); - } - catch (NoSuchCompanyException nsce) { - company = CompanyLocalServiceUtil.getCompanyById( - PortalInstances.getDefaultCompanyId()); - } - - request.setAttribute(WebKeys.COMPANY, company); - } - - return company; - } - - public Company getCompany(PortletRequest portletRequest) - throws PortalException, SystemException { - - return getCompany(getHttpServletRequest(portletRequest)); - } - - public long getCompanyId(HttpServletRequest request) { - return PortalInstances.getCompanyId(request); - } - - public long getCompanyId(PortletRequest portletRequest) { - return getCompanyId(getHttpServletRequest(portletRequest)); - } - - public long[] getCompanyIds() { - return PortalInstances.getCompanyIds(); - } - - public String getComputerAddress() { - return _computerAddress; - } - - public String getComputerName() { - return _computerName; - } - - public String getControlPanelCategory( - String portletId, ThemeDisplay themeDisplay) - throws SystemException { - - for (String category : PortletCategoryKeys.ALL) { - List portlets = getControlPanelPortlets( - category, themeDisplay); - - for (Portlet portlet : portlets) { - if (portlet.getPortletId().equals(portletId)) { - return category; - } - } - } - - return StringPool.BLANK; - } - - public String getControlPanelFullURL( - long scopeGroupId, String ppid, Map params) - throws PortalException, SystemException { - - StringBundler sb = new StringBundler(6); - - Group group = GroupLocalServiceUtil.getGroup(scopeGroupId); - - Company company = CompanyLocalServiceUtil.getCompany( - group.getCompanyId()); - - sb.append( - getPortalURL( - company.getVirtualHostname(), getPortalPort(false), false)); - sb.append(getPathFriendlyURLPrivateGroup()); - sb.append(GroupConstants.CONTROL_PANEL_FRIENDLY_URL); - sb.append(PropsValues.CONTROL_PANEL_LAYOUT_FRIENDLY_URL); - - if (params != null) { - params = new HashMap(params); - } - else { - params = new HashMap(); - } - - params.put("p_p_id", new String[] {ppid}); - params.put("p_p_lifecycle", new String[] {"0"}); - params.put( - "p_p_state", new String[] {WindowState.MAXIMIZED.toString()}); - params.put("p_p_mode", new String[] {PortletMode.VIEW.toString()}); - - sb.append(HttpUtil.parameterMapToString(params, true)); - - return sb.toString(); - } - - public Set getControlPanelPortlets(long companyId, String category) - throws SystemException { - - Set portletsSet = new TreeSet( - new PortletControlPanelWeightComparator()); - - List portletsList = PortletLocalServiceUtil.getPortlets( - companyId); - - for (Portlet portlet : portletsList) { - if (category.equals(portlet.getControlPanelEntryCategory())) { - portletsSet.add(portlet); - } - } - - return portletsSet; - } - - public List getControlPanelPortlets( - String category, ThemeDisplay themeDisplay) - throws SystemException { - - Set portlets = getControlPanelPortlets( - themeDisplay.getCompanyId(), category); - - return filterControlPanelPortlets(portlets, category, themeDisplay); - } - - public String getCreateAccountURL( - HttpServletRequest request, ThemeDisplay themeDisplay) - throws Exception { - - if (Validator.isNull(PropsValues.COMPANY_SECURITY_STRANGERS_URL)) { - PortletURL createAccountURL = PortletURLFactoryUtil.create( - request, PortletKeys.LOGIN, themeDisplay.getPlid(), - PortletRequest.RENDER_PHASE); - - createAccountURL.setWindowState(WindowState.MAXIMIZED); - createAccountURL.setPortletMode(PortletMode.VIEW); - - createAccountURL.setParameter("saveLastPath", "0"); - createAccountURL.setParameter( - "struts_action", "/login/create_account"); - - return createAccountURL.toString(); - } - - try { - Layout layout = LayoutLocalServiceUtil.getFriendlyURLLayout( - themeDisplay.getScopeGroupId(), false, - PropsValues.COMPANY_SECURITY_STRANGERS_URL); - - return PortalUtil.getLayoutURL(layout, themeDisplay); - } - catch (NoSuchLayoutException nsle) { - } - - return StringPool.BLANK; - } - - public String getCurrentCompleteURL(HttpServletRequest request) { - String currentCompleteURL = (String)request.getAttribute( - WebKeys.CURRENT_COMPLETE_URL); - - if (currentCompleteURL == null) { - currentCompleteURL = HttpUtil.getCompleteURL(request); - - request.setAttribute( - WebKeys.CURRENT_COMPLETE_URL, currentCompleteURL); - } - - return currentCompleteURL; - } - - public String getCurrentURL(HttpServletRequest request) { - String currentURL = (String)request.getAttribute(WebKeys.CURRENT_URL); - - if (currentURL != null) { - return currentURL; - } - - currentURL = ParamUtil.getString(request, "currentURL"); - - if (Validator.isNull(currentURL)) { - currentURL = HttpUtil.getCompleteURL(request); - - if ((Validator.isNotNull(currentURL)) && - (currentURL.indexOf(_J_SECURITY_CHECK) == -1)) { - - currentURL = currentURL.substring( - currentURL.indexOf(Http.PROTOCOL_DELIMITER) + - Http.PROTOCOL_DELIMITER.length()); - - currentURL = currentURL.substring( - currentURL.indexOf(CharPool.SLASH)); - } - - if (Validator.isNotNull(currentURL) && - FacebookUtil.isFacebook(currentURL)) { - - String[] facebookData = FacebookUtil.getFacebookData(request); - - currentURL = - FacebookUtil.FACEBOOK_APPS_URL + facebookData[0] + - facebookData[2]; - } - } - - if (Validator.isNull(currentURL)) { - currentURL = getPathMain(); - } - - request.setAttribute(WebKeys.CURRENT_URL, currentURL); - - return currentURL; - } - - public String getCurrentURL(PortletRequest portletRequest) { - return (String)portletRequest.getAttribute(WebKeys.CURRENT_URL); - } - - public String getCustomSQLFunctionIsNotNull() { - return PropsValues.CUSTOM_SQL_FUNCTION_ISNOTNULL; - } - - public String getCustomSQLFunctionIsNull() { - return PropsValues.CUSTOM_SQL_FUNCTION_ISNULL; - } - - public Date getDate(int month, int day, int year) { - try { - return getDate(month, day, year, null); - } - catch (PortalException pe) { - throw new RuntimeException(); - } - } - - public Date getDate( - int month, int day, int year, int hour, int min, PortalException pe) - throws PortalException { - - return getDate(month, day, year, hour, min, null, pe); - } - - public Date getDate( - int month, int day, int year, int hour, int min, TimeZone timeZone, - PortalException pe) - throws PortalException { - - if (!Validator.isGregorianDate(month, day, year)) { - if (pe != null) { - throw pe; - } - else { - return null; - } - } - else { - Calendar cal = null; - - if (timeZone == null) { - cal = CalendarFactoryUtil.getCalendar(); - } - else { - cal = CalendarFactoryUtil.getCalendar(timeZone); - } - - if ((hour == -1) || (min == -1)) { - cal.set(year, month, day, 0, 0, 0); - } - else { - cal.set(year, month, day, hour, min, 0); - } - - cal.set(Calendar.MILLISECOND, 0); - - Date date = cal.getTime(); - - /*if (timeZone != null && - cal.before(CalendarFactoryUtil.getCalendar(timeZone))) { - - throw pe; - }*/ - - return date; - } - } - - public Date getDate(int month, int day, int year, PortalException pe) - throws PortalException { - - return getDate(month, day, year, null, pe); - } - - public Date getDate( - int month, int day, int year, TimeZone timeZone, PortalException pe) - throws PortalException { - - return getDate(month, day, year, -1, -1, timeZone, pe); - } - - public long getDefaultCompanyId() { - return PortalInstances.getDefaultCompanyId(); - } - - public long getDigestAuthUserId(HttpServletRequest request) - throws PortalException, SystemException { - - long userId = 0; - - String authorizationHeader = request.getHeader( - HttpHeaders.AUTHORIZATION); - - if (Validator.isNull(authorizationHeader) || - !authorizationHeader.startsWith("Digest ")) { - - return userId; - } - - authorizationHeader = authorizationHeader.substring("Digest ".length()); - authorizationHeader = StringUtil.replace( - authorizationHeader, CharPool.COMMA, CharPool.NEW_LINE); - - UnicodeProperties authorizationProperties = new UnicodeProperties(); - - authorizationProperties.fastLoad(authorizationHeader); - - String username = StringUtil.unquote( - authorizationProperties.getProperty("username")); - String realm = StringUtil.unquote( - authorizationProperties.getProperty("realm")); - String nonce = StringUtil.unquote( - authorizationProperties.getProperty("nonce")); - String uri = StringUtil.unquote( - authorizationProperties.getProperty("uri")); - String response = StringUtil.unquote( - authorizationProperties.getProperty("response")); - - if (Validator.isNull(username) || Validator.isNull(realm) || - Validator.isNull(nonce) || Validator.isNull(uri) || - Validator.isNull(response)) { - - return userId; - } - - if (!realm.equals(PORTAL_REALM) || - !uri.equals(request.getRequestURI())) { - - return userId; - } - - if (!NonceUtil.verify(nonce)) { - return userId; - } - - long companyId = PortalInstances.getCompanyId(request); - - userId = UserLocalServiceUtil.authenticateForDigest( - companyId, username, realm, nonce, request.getMethod(), uri, - response); - - return userId; - } - - public String getEmailFromAddress( - PortletPreferences preferences, long companyId, String defaultValue) - throws SystemException { - - if (Validator.isNull(defaultValue)) { - defaultValue = PrefsPropsUtil.getString( - companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS); - } - - return preferences.getValue("emailFromAddress", defaultValue); - } - - public String getEmailFromName( - PortletPreferences preferences, long companyId, String defaultValue) - throws SystemException { - - if (Validator.isNull(defaultValue)) { - defaultValue = PrefsPropsUtil.getString( - companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME); - } - - return preferences.getValue("emailFromName", defaultValue); - } - - public Map getExpandoBridgeAttributes( - ExpandoBridge expandoBridge, PortletRequest portletRequest) - throws PortalException, SystemException { - - Map attributes = - new HashMap(); - - List names = new ArrayList(); - - Enumeration enu = portletRequest.getParameterNames(); - - while (enu.hasMoreElements()) { - String param = enu.nextElement(); - - if (param.indexOf("ExpandoAttributeName--") != -1) { - String name = ParamUtil.getString(portletRequest, param); - - names.add(name); - } - } - - for (String name : names) { - int type = expandoBridge.getAttributeType(name); - - UnicodeProperties properties = expandoBridge.getAttributeProperties( - name); - - String displayType = GetterUtil.getString( - properties.getProperty( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE), - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX); - - Serializable value = getExpandoValue( - portletRequest, "ExpandoAttribute--" + name + "--", type, - displayType); - - attributes.put(name, value); - } - - return attributes; - } - - public Map getExpandoBridgeAttributes( - ExpandoBridge expandoBridge, - UploadPortletRequest uploadPortletRequest) - throws PortalException, SystemException { - - Map attributes = - new HashMap(); - - List names = new ArrayList(); - - Enumeration enu = uploadPortletRequest.getParameterNames(); - - while (enu.hasMoreElements()) { - String param = enu.nextElement(); - - if (param.indexOf("ExpandoAttributeName--") != -1) { - String name = ParamUtil.getString(uploadPortletRequest, param); - - names.add(name); - } - } - - for (String name : names) { - int type = expandoBridge.getAttributeType(name); - - UnicodeProperties properties = expandoBridge.getAttributeProperties( - name); - - String displayType = GetterUtil.getString( - properties.getProperty( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE), - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX); - - Serializable value = getExpandoValue( - uploadPortletRequest, "ExpandoAttribute--" + name + "--", type, - displayType); - - attributes.put(name, value); - } - - return attributes; - } - - public Serializable getExpandoValue( - PortletRequest portletRequest, String name, int type, - String displayType) - throws PortalException, SystemException { - - Serializable value = null; - - if (type == ExpandoColumnConstants.BOOLEAN) { - value = ParamUtil.getBoolean(portletRequest, name); - } - else if (type == ExpandoColumnConstants.BOOLEAN_ARRAY) { - } - else if (type == ExpandoColumnConstants.DATE) { - int valueDateMonth = ParamUtil.getInteger( - portletRequest, name + "Month"); - int valueDateDay = ParamUtil.getInteger( - portletRequest, name + "Day"); - int valueDateYear = ParamUtil.getInteger( - portletRequest, name + "Year"); - int valueDateHour = ParamUtil.getInteger( - portletRequest, name + "Hour"); - int valueDateMinute = ParamUtil.getInteger( - portletRequest, name + "Minute"); - int valueDateAmPm = ParamUtil.getInteger( - portletRequest, name + "AmPm"); - - if (valueDateAmPm == Calendar.PM) { - valueDateHour += 12; - } - - TimeZone timeZone = null; - - User user = getUser(portletRequest); - - if (user != null) { - timeZone = user.getTimeZone(); - } - - value = getDate( - valueDateMonth, valueDateDay, valueDateYear, valueDateHour, - valueDateMinute, timeZone, new ValueDataException()); - } - else if (type == ExpandoColumnConstants.DATE_ARRAY) { - } - else if (type == ExpandoColumnConstants.DOUBLE) { - value = ParamUtil.getDouble(portletRequest, name); - } - else if (type == ExpandoColumnConstants.DOUBLE_ARRAY) { - String[] values = portletRequest.getParameterValues(name); - - if (displayType.equals( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { - - values = StringUtil.splitLines(values[0]); - } - - value = GetterUtil.getDoubleValues(values); - } - else if (type == ExpandoColumnConstants.FLOAT) { - value = ParamUtil.getFloat(portletRequest, name); - } - else if (type == ExpandoColumnConstants.FLOAT_ARRAY) { - String[] values = portletRequest.getParameterValues(name); - - if (displayType.equals( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { - - values = StringUtil.splitLines(values[0]); - } - - value = GetterUtil.getFloatValues(values); - } - else if (type == ExpandoColumnConstants.INTEGER) { - value = ParamUtil.getInteger(portletRequest, name); - } - else if (type == ExpandoColumnConstants.INTEGER_ARRAY) { - String[] values = portletRequest.getParameterValues(name); - - if (displayType.equals( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { - - values = StringUtil.splitLines(values[0]); - } - - value = GetterUtil.getIntegerValues(values); - } - else if (type == ExpandoColumnConstants.LONG) { - value = ParamUtil.getLong(portletRequest, name); - } - else if (type == ExpandoColumnConstants.LONG_ARRAY) { - String[] values = portletRequest.getParameterValues(name); - - if (displayType.equals( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { - - values = StringUtil.splitLines(values[0]); - } - - value = GetterUtil.getLongValues(values); - } - else if (type == ExpandoColumnConstants.SHORT) { - value = ParamUtil.getShort(portletRequest, name); - } - else if (type == ExpandoColumnConstants.SHORT_ARRAY) { - String[] values = portletRequest.getParameterValues(name); - - if (displayType.equals( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { - - values = StringUtil.splitLines(values[0]); - } - - value = GetterUtil.getShortValues(values); - } - else if (type == ExpandoColumnConstants.STRING_ARRAY) { - value = portletRequest.getParameterValues(name); - } - else { - value = ParamUtil.getString(portletRequest, name); - } - - return value; - } - - public Serializable getExpandoValue( - UploadPortletRequest uploadPortletRequest, String name, int type, - String displayType) - throws PortalException, SystemException { - - Serializable value = null; - - if (type == ExpandoColumnConstants.BOOLEAN) { - value = ParamUtil.getBoolean(uploadPortletRequest, name); - } - else if (type == ExpandoColumnConstants.BOOLEAN_ARRAY) { - } - else if (type == ExpandoColumnConstants.DATE) { - int valueDateMonth = ParamUtil.getInteger( - uploadPortletRequest, name + "Month"); - int valueDateDay = ParamUtil.getInteger( - uploadPortletRequest, name + "Day"); - int valueDateYear = ParamUtil.getInteger( - uploadPortletRequest, name + "Year"); - int valueDateHour = ParamUtil.getInteger( - uploadPortletRequest, name + "Hour"); - int valueDateMinute = ParamUtil.getInteger( - uploadPortletRequest, name + "Minute"); - int valueDateAmPm = ParamUtil.getInteger( - uploadPortletRequest, name + "AmPm"); - - if (valueDateAmPm == Calendar.PM) { - valueDateHour += 12; - } - - TimeZone timeZone = null; - - User user = getUser(uploadPortletRequest); - - if (user != null) { - timeZone = user.getTimeZone(); - } - - value = getDate( - valueDateMonth, valueDateDay, valueDateYear, valueDateHour, - valueDateMinute, timeZone, new ValueDataException()); - } - else if (type == ExpandoColumnConstants.DATE_ARRAY) { - } - else if (type == ExpandoColumnConstants.DOUBLE) { - value = ParamUtil.getDouble(uploadPortletRequest, name); - } - else if (type == ExpandoColumnConstants.DOUBLE_ARRAY) { - String[] values = uploadPortletRequest.getParameterValues(name); - - if (displayType.equals( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { - - values = StringUtil.splitLines(values[0]); - } - - value = GetterUtil.getDoubleValues(values); - } - else if (type == ExpandoColumnConstants.FLOAT) { - value = ParamUtil.getFloat(uploadPortletRequest, name); - } - else if (type == ExpandoColumnConstants.FLOAT_ARRAY) { - String[] values = uploadPortletRequest.getParameterValues(name); - - if (displayType.equals( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { - - values = StringUtil.splitLines(values[0]); - } - - value = GetterUtil.getFloatValues(values); - } - else if (type == ExpandoColumnConstants.INTEGER) { - value = ParamUtil.getInteger(uploadPortletRequest, name); - } - else if (type == ExpandoColumnConstants.INTEGER_ARRAY) { - String[] values = uploadPortletRequest.getParameterValues(name); - - if (displayType.equals( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { - - values = StringUtil.splitLines(values[0]); - } - - value = GetterUtil.getIntegerValues(values); - } - else if (type == ExpandoColumnConstants.LONG) { - value = ParamUtil.getLong(uploadPortletRequest, name); - } - else if (type == ExpandoColumnConstants.LONG_ARRAY) { - String[] values = uploadPortletRequest.getParameterValues(name); - - if (displayType.equals( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { - - values = StringUtil.splitLines(values[0]); - } - - value = GetterUtil.getLongValues(values); - } - else if (type == ExpandoColumnConstants.SHORT) { - value = ParamUtil.getShort(uploadPortletRequest, name); - } - else if (type == ExpandoColumnConstants.SHORT_ARRAY) { - String[] values = uploadPortletRequest.getParameterValues(name); - - if (displayType.equals( - ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { - - values = StringUtil.splitLines(values[0]); - } - - value = GetterUtil.getShortValues(values); - } - else if (type == ExpandoColumnConstants.STRING_ARRAY) { - value = uploadPortletRequest.getParameterValues(name); - } - else { - value = ParamUtil.getString(uploadPortletRequest, name); - } - - return value; - } - - public String getFacebookURL( - Portlet portlet, String facebookCanvasPageURL, - ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - String facebookURL = getServletURL( - portlet, FacebookUtil.FACEBOOK_SERVLET_PATH + facebookCanvasPageURL, - themeDisplay); - - if (!facebookURL.endsWith(StringPool.SLASH)) { - facebookURL += StringPool.SLASH; - } - - return facebookURL; - } - - public String getFirstPageLayoutTypes(PageContext pageContext) { - StringBundler sb = new StringBundler(); - - for (String type : PropsValues.LAYOUT_TYPES) { - if (isLayoutFirstPageable(type)) { - sb.append( - LanguageUtil.get(pageContext, "layout.types." + type)); - sb.append(StringPool.COMMA); - sb.append(StringPool.SPACE); - } - } - - if (sb.index() >= 2) { - sb.setIndex(sb.index() - 2); - } - - return sb.toString(); - } - - public String getGlobalLibDir() { - return PropsValues.LIFERAY_LIB_GLOBAL_DIR; - } - - public String getGoogleGadgetURL(Portlet portlet, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getServletURL( - portlet, PropsValues.GOOGLE_GADGET_SERVLET_MAPPING, themeDisplay); - } - - public String getGroupFriendlyURL( - Group group, boolean privateLayoutSet, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getGroupFriendlyURL( - group, privateLayoutSet, themeDisplay, false); - } - - public String[] getGroupPermissions(HttpServletRequest request) { - return request.getParameterValues("groupPermissions"); - } - - public String[] getGroupPermissions(PortletRequest portletRequest) { - return portletRequest.getParameterValues("groupPermissions"); - } - - public String[] getGuestPermissions(HttpServletRequest request) { - return request.getParameterValues("guestPermissions"); - } - - public String[] getGuestPermissions(PortletRequest portletRequest) { - return portletRequest.getParameterValues("guestPermissions"); - } - - public String getHomeURL(HttpServletRequest request) - throws PortalException, SystemException { - - String portalURL = getPortalURL(request); - - return portalURL + _pathContext + getRelativeHomeURL(request); - } - - public String getHost(HttpServletRequest request) { - request = getOriginalServletRequest(request); - - String host = request.getHeader("Host"); - - if (host != null) { - host = host.trim().toLowerCase(); - - int pos = host.indexOf(':'); - - if (pos >= 0) { - host = host.substring(0, pos); - } - } - else { - host = null; - } - - return host; - } - - public String getHost(PortletRequest portletRequest) { - return getHost(getHttpServletRequest(portletRequest)); - } - - public HttpServletRequest getHttpServletRequest( - PortletRequest portletRequest) { - - PortletRequestImpl portletRequestImpl = - PortletRequestImpl.getPortletRequestImpl(portletRequest); - - return portletRequestImpl.getHttpServletRequest(); - } - - public HttpServletResponse getHttpServletResponse( - PortletResponse portletResponse) { - - PortletResponseImpl portletResponseImpl = - PortletResponseImpl.getPortletResponseImpl(portletResponse); - - return portletResponseImpl.getHttpServletResponse(); - } - - public String getJournalArticleActualURL( - long groupId, String mainPath, String friendlyURL, - Map params, Map requestContext) - throws PortalException, SystemException { - - String articleUrlTitle = friendlyURL.substring( - JournalArticleConstants.CANONICAL_URL_SEPARATOR.length()); - - JournalArticle journalArticle = - JournalArticleLocalServiceUtil.getArticleByUrlTitle( - groupId, articleUrlTitle); - - Layout layout = LayoutLocalServiceUtil.getLayoutByUuidAndGroupId( - journalArticle.getLayoutUuid(), groupId); - - String layoutActualURL = getLayoutActualURL(layout, mainPath); - - InheritableMap actualParams = - new InheritableMap(); - - if (params != null) { - actualParams.setParentMap(params); - } - - UnicodeProperties typeSettingsProperties = - layout.getTypeSettingsProperties(); - - String defaultAssetPublisherPortletId = typeSettingsProperties.get( - LayoutTypePortletConstants.DEFAULT_ASSET_PUBLISHER_PORTLET_ID); - - String currentDefaultAssetPublisherPortletId = - defaultAssetPublisherPortletId; - - if (Validator.isNull(defaultAssetPublisherPortletId)) { - defaultAssetPublisherPortletId = - PortletKeys.ASSET_PUBLISHER + - LayoutTypePortletImpl.getFullInstanceSeparator(); - } - - HttpServletRequest request = - (HttpServletRequest)requestContext.get("request"); - - if (Validator.isNull(currentDefaultAssetPublisherPortletId)) { - String actualPortletAuthenticationToken = AuthTokenUtil.getToken( - request, layout.getPlid(), defaultAssetPublisherPortletId); - - actualParams.put( - "p_p_auth", new String[] {actualPortletAuthenticationToken}); - } - - actualParams.put( - "p_p_id", new String[] {defaultAssetPublisherPortletId}); - actualParams.put("p_p_lifecycle", new String[] {"0"}); - - if (Validator.isNull(currentDefaultAssetPublisherPortletId)) { - actualParams.put( - "p_p_state", new String[] {WindowState.MAXIMIZED.toString()}); - } - - actualParams.put("p_p_mode", new String[] {"view"}); - actualParams.put( - "p_j_a_id", new String[] {String.valueOf(journalArticle.getId())}); - - String namespace = getPortletNamespace(defaultAssetPublisherPortletId); - - actualParams.put( - namespace + "struts_action", - new String[] {"/asset_publisher/view_content"}); - actualParams.put( - namespace + "type", - new String[] {JournalArticleAssetRendererFactory.TYPE}); - actualParams.put( - namespace + "urlTitle", - new String[] {journalArticle.getUrlTitle()}); - - String queryString = HttpUtil.parameterMapToString(actualParams, false); - - if (layoutActualURL.contains(StringPool.QUESTION)) { - layoutActualURL = - layoutActualURL + StringPool.AMPERSAND + queryString; - } - else { - layoutActualURL = - layoutActualURL + StringPool.QUESTION + queryString; - } - - Locale locale = getLocale(request); - - addPageSubtitle(journalArticle.getTitle(locale), request); - addPageDescription(journalArticle.getDescription(locale), request); - - List assetTags = AssetTagLocalServiceUtil.getTags( - JournalArticle.class.getName(), journalArticle.getPrimaryKey()); - - if (!assetTags.isEmpty()) { - addPageKeywords( - ListUtil.toString(assetTags, AssetTag.NAME_ACCESSOR), - request); - } - - return layoutActualURL; - } - - public String getJsSafePortletId(String portletId) { - return JS.getSafeName(portletId); - } - - public String getLayoutActualURL(Layout layout) { - return getLayoutActualURL(layout, getPathMain()); - } - - public String getLayoutActualURL(Layout layout, String mainPath) { - Map variables = new HashMap(); - - variables.put("liferay:groupId", String.valueOf(layout.getGroupId())); - variables.put("liferay:mainPath", mainPath); - variables.put("liferay:plid", String.valueOf(layout.getPlid())); - - if (layout instanceof VirtualLayout) { - variables.put( - "liferay:pvlsgid", String.valueOf(layout.getGroupId())); - } - else { - variables.put("liferay:pvlsgid", "0"); - } - - LayoutType layoutType = layout.getLayoutType(); - - UnicodeProperties typeSettingsProperties = - layoutType.getTypeSettingsProperties(); - - variables.putAll(typeSettingsProperties); - - LayoutSettings layoutSettings = LayoutSettings.getInstance(layout); - - return layoutSettings.getURL(variables); - } - - public String getLayoutActualURL( - long groupId, boolean privateLayout, String mainPath, - String friendlyURL) - throws PortalException, SystemException { - - return getLayoutActualURL( - groupId, privateLayout, mainPath, friendlyURL, null, null); - } - - public String getLayoutActualURL( - long groupId, boolean privateLayout, String mainPath, - String friendlyURL, Map params, - Map requestContext) - throws PortalException, SystemException { - - Layout layout = null; - String queryString = StringPool.BLANK; - - if (Validator.isNull(friendlyURL)) { - List layouts = LayoutLocalServiceUtil.getLayouts( - groupId, privateLayout, - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); - - if (!layouts.isEmpty()) { - layout = layouts.get(0); - } - else { - throw new NoSuchLayoutException( - "{groupId=" + groupId + ",privateLayout=" + privateLayout + - "} does not have any layouts"); - } - } - else { - Object[] friendlyURLMapper = getPortletFriendlyURLMapper( - groupId, privateLayout, friendlyURL, params, requestContext); - - layout = (Layout)friendlyURLMapper[0]; - queryString = (String)friendlyURLMapper[1]; - } - - String layoutActualURL = getLayoutActualURL(layout, mainPath); - - if (Validator.isNotNull(queryString)) { - layoutActualURL = layoutActualURL.concat(queryString); - } - else if (params.isEmpty()) { - LayoutType layoutType = layout.getLayoutType(); - - UnicodeProperties typeSettingsProperties = - layoutType.getTypeSettingsProperties(); - - queryString = typeSettingsProperties.getProperty("query-string"); - - if (Validator.isNotNull(queryString) && - layoutActualURL.contains(StringPool.QUESTION)) { - - layoutActualURL = layoutActualURL.concat( - StringPool.AMPERSAND).concat(queryString); - } - } - - return layoutActualURL; - } - - public String getLayoutEditPage(Layout layout) { - LayoutSettings layoutSettings = LayoutSettings.getInstance( - layout.getType()); - - return layoutSettings.getEditPage(); - } - - public String getLayoutEditPage(String type) { - LayoutSettings layoutSettings = LayoutSettings.getInstance(type); - - return layoutSettings.getEditPage(); - } - - public String getLayoutFriendlyURL(Layout layout, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - if (!isLayoutFriendliable(layout)) { - return null; - } - - String groupFriendlyURL = getGroupFriendlyURL( - layout.getGroup(), layout.isPrivateLayout(), themeDisplay); - - return groupFriendlyURL.concat(layout.getFriendlyURL()); - } - - public String getLayoutFriendlyURL( - Layout layout, ThemeDisplay themeDisplay, Locale locale) - throws PortalException, SystemException { - - String i18nLanguageId = themeDisplay.getI18nLanguageId(); - String i18nPath = themeDisplay.getI18nPath(); - - try { - String tempI18nLanguageId = null; - String tempI18nPath = null; - - if (((I18nFilter.getLanguageIds().contains(locale.toString())) && - ((PropsValues.LOCALE_PREPEND_FRIENDLY_URL_STYLE == 1) && - (!locale.equals(LocaleUtil.getDefault())))) || - (PropsValues.LOCALE_PREPEND_FRIENDLY_URL_STYLE == 2)) { - - tempI18nLanguageId = locale.toString(); - tempI18nPath = buildI18NPath(locale); - } - - themeDisplay.setI18nLanguageId(tempI18nLanguageId); - themeDisplay.setI18nPath(tempI18nPath); - - return getLayoutFriendlyURL(layout, themeDisplay); - } - finally { - themeDisplay.setI18nLanguageId(i18nLanguageId); - themeDisplay.setI18nPath(i18nPath); - } - } - - public String getLayoutFullURL(Layout layout, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getLayoutFullURL(layout, themeDisplay, true); - } - - public String getLayoutFullURL( - Layout layout, ThemeDisplay themeDisplay, boolean doAsUser) - throws PortalException, SystemException { - - String layoutURL = getLayoutURL(layout, themeDisplay, doAsUser); - String portalURL = getPortalURL(layout, themeDisplay); - - if (StringUtil.startsWith(layoutURL, portalURL)) { - return layoutURL; - } - else { - return portalURL + layoutURL; - } - } - - public String getLayoutFullURL(long groupId, String portletId) - throws PortalException, SystemException { - - return getLayoutFullURL(groupId, portletId, false); - } - - public String getLayoutFullURL( - long groupId, String portletId, boolean secure) - throws PortalException, SystemException { - - long plid = getPlidFromPortletId(groupId, portletId); - - if (plid == LayoutConstants.DEFAULT_PLID) { - return null; - } - - StringBundler sb = new StringBundler(4); - - Layout layout = LayoutLocalServiceUtil.getLayout(plid); - - Group group = GroupLocalServiceUtil.getGroup(groupId); - - if (group.isLayout()) { - long parentGroupId = group.getParentGroupId(); - - if (parentGroupId > 0) { - group = GroupLocalServiceUtil.getGroup(parentGroupId); - } - } - - String virtualHostname = null; - - LayoutSet layoutSet = layout.getLayoutSet(); - - if (Validator.isNotNull(layoutSet.getVirtualHostname())) { - virtualHostname = layoutSet.getVirtualHostname(); - } - else { - Company company = CompanyLocalServiceUtil.getCompany( - layout.getCompanyId()); - - virtualHostname = company.getVirtualHostname(); - } - - String portalURL = getPortalURL( - virtualHostname, getPortalPort(secure), secure); - - sb.append(portalURL); - - if (layout.isPrivateLayout()) { - if (group.isUser()) { - sb.append(getPathFriendlyURLPrivateUser()); - } - else { - sb.append(getPathFriendlyURLPrivateGroup()); - } - } - else { - sb.append(getPathFriendlyURLPublic()); - } - - sb.append(group.getFriendlyURL()); - sb.append(layout.getFriendlyURL()); - - return sb.toString(); - } - - public String getLayoutFullURL(ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getLayoutFullURL(themeDisplay.getLayout(), themeDisplay); - } - - public String getLayoutSetFriendlyURL( - LayoutSet layoutSet, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - String virtualHostname = layoutSet.getVirtualHostname(); - - if (Validator.isNull(virtualHostname) && - Validator.isNotNull(PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME) && - !layoutSet.isPrivateLayout()) { - - try { - Group group = GroupLocalServiceUtil.getGroup( - themeDisplay.getCompanyId(), - PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME); - - if (layoutSet.getGroupId() == group.getGroupId()) { - Company company = themeDisplay.getCompany(); - - virtualHostname = company.getVirtualHostname(); - } - } - catch (Exception e) { - _log.error(e, e); - } - } - - if (Validator.isNotNull(virtualHostname)) { - String portalURL = getPortalURL( - virtualHostname, themeDisplay.getServerPort(), - themeDisplay.isSecure()); - - // Use the layout set's virtual host setting only if the layout set - // is already used for the current request - - long curLayoutSetId = - themeDisplay.getLayout().getLayoutSet().getLayoutSetId(); - - if ((layoutSet.getLayoutSetId() != curLayoutSetId) || - (portalURL.startsWith(themeDisplay.getURLPortal()))) { - - String layoutSetFriendlyURL = StringPool.BLANK; - - if (themeDisplay.isI18n()) { - layoutSetFriendlyURL = themeDisplay.getI18nPath(); - } - - return portalURL + _pathContext + layoutSetFriendlyURL; - } - } - - Group group = GroupLocalServiceUtil.getGroup(layoutSet.getGroupId()); - - String friendlyURL = null; - - if (layoutSet.isPrivateLayout()) { - if (group.isUser()) { - friendlyURL = _PRIVATE_USER_SERVLET_MAPPING; - } - else { - friendlyURL = _PRIVATE_GROUP_SERVLET_MAPPING; - } - } - else { - friendlyURL = _PUBLIC_GROUP_SERVLET_MAPPING; - } - - if (themeDisplay.isI18n()) { - friendlyURL = themeDisplay.getI18nPath() + friendlyURL; - } - - return _pathContext + friendlyURL + group.getFriendlyURL(); - } - - public String getLayoutTarget(Layout layout) { - UnicodeProperties typeSettingsProps = - layout.getTypeSettingsProperties(); - - String target = typeSettingsProps.getProperty("target"); - - if (Validator.isNull(target)) { - target = StringPool.BLANK; - } - else { - target = "target=\"" + HtmlUtil.escapeAttribute(target) + "\""; - } - - return target; - } - - public String getLayoutURL(Layout layout, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getLayoutURL(layout, themeDisplay, true); - } - - public String getLayoutURL( - Layout layout, ThemeDisplay themeDisplay, boolean doAsUser) - throws PortalException, SystemException { - - if (layout == null) { - return themeDisplay.getPathMain() + PATH_PORTAL_LAYOUT; - } - - if (!layout.isTypeURL()) { - String layoutFriendlyURL = getLayoutFriendlyURL( - layout, themeDisplay); - - if (Validator.isNotNull(layoutFriendlyURL)) { - layoutFriendlyURL = addPreservedParameters( - themeDisplay, layout, layoutFriendlyURL, doAsUser); - - return layoutFriendlyURL; - } - } - - String layoutURL = getLayoutActualURL(layout); - - layoutURL = addPreservedParameters( - themeDisplay, layout, layoutURL, doAsUser); - - return layoutURL; - } - - public String getLayoutURL(ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getLayoutURL(themeDisplay.getLayout(), themeDisplay); - } - - public String getLayoutViewPage(Layout layout) { - LayoutSettings layoutSettings = LayoutSettings.getInstance( - layout.getType()); - - return layoutSettings.getViewPage(); - } - - public String getLayoutViewPage(String type) { - LayoutSettings layoutSettings = LayoutSettings.getInstance(type); - - return layoutSettings.getViewPage(); - } - - public LiferayPortletRequest getLiferayPortletRequest( - PortletRequest portletRequest) { - - PortletRequestImpl portletRequestImpl = - PortletRequestImpl.getPortletRequestImpl(portletRequest); - - return portletRequestImpl; - } - - public LiferayPortletResponse getLiferayPortletResponse( - PortletResponse portletResponse) { - - PortletResponseImpl portletResponseImpl = - PortletResponseImpl.getPortletResponseImpl(portletResponse); - - return portletResponseImpl; - } - - public Locale getLocale(HttpServletRequest request) { - ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( - WebKeys.THEME_DISPLAY); - - if (themeDisplay != null) { - return themeDisplay.getLocale(); - } - else { - HttpSession session = request.getSession(); - - return (Locale)session.getAttribute(Globals.LOCALE_KEY); - } - } - - public Locale getLocale(RenderRequest renderRequest) { - return getLocale(getHttpServletRequest(renderRequest)); - } - - public String getMailId(String mx, String popPortletPrefix, Object... ids) { - StringBundler sb = new StringBundler(ids.length * 2 + 7); - - sb.append(StringPool.LESS_THAN); - sb.append(popPortletPrefix); - - if (!popPortletPrefix.endsWith(StringPool.PERIOD)) { - sb.append(StringPool.PERIOD); - } - - for (int i = 0; i < ids.length; i++) { - Object id = ids[i]; - - if (i != 0) { - sb.append(StringPool.PERIOD); - } - - sb.append(id); - } - - sb.append(StringPool.AT); - - if (Validator.isNotNull(PropsValues.POP_SERVER_SUBDOMAIN)) { - sb.append(PropsValues.POP_SERVER_SUBDOMAIN); - sb.append(StringPool.PERIOD); - } - - sb.append(mx); - sb.append(StringPool.GREATER_THAN); - - return sb.toString(); - } - - public String getNetvibesURL(Portlet portlet, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getServletURL( - portlet, PropsValues.NETVIBES_SERVLET_MAPPING, themeDisplay); - } - - public String getNewPortletTitle( - String portletTitle, String oldScopeName, String newScopeName) { - - if (portletTitle.endsWith(" (" + oldScopeName + ")")) { - int pos = portletTitle.lastIndexOf(" (" + oldScopeName + ")"); - - portletTitle = portletTitle.substring(0, pos); - } - - if (Validator.isNull(newScopeName)) { - return portletTitle; - } - - StringBundler sb = new StringBundler(5); - - sb.append(portletTitle); - sb.append(StringPool.SPACE); - sb.append(StringPool.OPEN_PARENTHESIS); - sb.append(newScopeName); - sb.append(StringPool.CLOSE_PARENTHESIS); - - return sb.toString(); - } - - public HttpServletRequest getOriginalServletRequest( - HttpServletRequest request) { - - HttpServletRequest originalRequest = request; - - while (originalRequest.getClass().getName().startsWith( - "com.liferay.")) { - - // Get original request so that portlets inside portlets render - // properly - - originalRequest = (HttpServletRequest) - ((HttpServletRequestWrapper)originalRequest).getRequest(); - } - - return originalRequest; - } - - public String getOuterPortletId(HttpServletRequest request) { - String outerPortletId = (String)request.getAttribute( - WebKeys.OUTER_PORTLET_ID); - - if (outerPortletId == null) { - outerPortletId = request.getParameter("p_o_p_id"); - } - - return outerPortletId; - } - - public long getParentGroupId(long groupId) - throws PortalException, SystemException { - - if (groupId <= 0) { - return 0; - } - - Group group = GroupLocalServiceUtil.getGroup(groupId); - - long parentGroupId = groupId; - - if (group.isLayout()) { - parentGroupId = group.getParentGroupId(); - } - - return parentGroupId; - } - - public String getPathContext() { - return _pathContext; - } - - public String getPathFriendlyURLPrivateGroup() { - return _pathFriendlyURLPrivateGroup; - } - - public String getPathFriendlyURLPrivateUser() { - return _pathFriendlyURLPrivateUser; - } - - public String getPathFriendlyURLPublic() { - return _pathFriendlyURLPublic; - } - - public String getPathImage() { - return _pathImage; - } - - public String getPathMain() { - return _pathMain; - } - - public String getPathProxy() { - return _pathProxy; - } - - public long getPlidFromFriendlyURL(long companyId, String friendlyURL) { - if (Validator.isNull(friendlyURL)) { - return LayoutConstants.DEFAULT_PLID; - } - - String[] urlParts = friendlyURL.split("\\/", 4); - - if ((friendlyURL.charAt(0) != CharPool.SLASH) && - (urlParts.length != 4)) { - - return LayoutConstants.DEFAULT_PLID; - } - - boolean privateLayout = true; - - String urlPrefix = StringPool.SLASH + urlParts[1]; - - if (_PUBLIC_GROUP_SERVLET_MAPPING.equals(urlPrefix)) { - privateLayout = false; - } - else if (_PRIVATE_GROUP_SERVLET_MAPPING.equals(urlPrefix) || - _PRIVATE_USER_SERVLET_MAPPING.equals(urlPrefix)) { - - privateLayout = true; - } - else { - return LayoutConstants.DEFAULT_PLID; - } - - Group group = null; - - try { - group = GroupLocalServiceUtil.getFriendlyURLGroup( - companyId, StringPool.SLASH + urlParts[2]); - } - catch (Exception e) { - } - - if (group != null) { - Layout layout = null; - - try { - String layoutFriendlyURL = null; - - if (urlParts.length == 4) { - layoutFriendlyURL = StringPool.SLASH + urlParts[3]; - - layout = LayoutLocalServiceUtil.getFriendlyURLLayout( - group.getGroupId(), privateLayout, layoutFriendlyURL); - } - else { - List layouts = LayoutLocalServiceUtil.getLayouts( - group.getGroupId(), privateLayout, - LayoutConstants.DEFAULT_PARENT_LAYOUT_ID, true, 0, 1); - - if (!layouts.isEmpty()) { - layout = layouts.get(0); - } - else { - return LayoutConstants.DEFAULT_PLID; - } - } - - return layout.getPlid(); - } - catch (Exception e) { - } - } - - return LayoutConstants.DEFAULT_PLID; - } - - public long getPlidFromPortletId( - long groupId, boolean privateLayout, String portletId) - throws PortalException, SystemException { - - long plid = LayoutConstants.DEFAULT_PLID; - - StringBundler sb = new StringBundler(5); - - sb.append(groupId); - sb.append(StringPool.SPACE); - sb.append(privateLayout); - sb.append(StringPool.SPACE); - sb.append(portletId); - - String key = sb.toString(); - - Long plidObj = _plidToPortletIdMap.get(key); - - if (plidObj == null) { - plid = doGetPlidFromPortletId(groupId, privateLayout, portletId); - - if (plid != LayoutConstants.DEFAULT_PLID) { - _plidToPortletIdMap.put(key, plid); - } - } - else { - plid = plidObj.longValue(); - - boolean validPlid = false; - - try { - Layout layout = LayoutLocalServiceUtil.getLayout(plid); - - LayoutTypePortlet layoutTypePortlet = - (LayoutTypePortlet)layout.getLayoutType(); - - if (layoutTypePortlet.hasDefaultScopePortletId( - groupId, portletId)) { - - validPlid = true; - } - } - catch (Exception e) { - } - - if (!validPlid) { - _plidToPortletIdMap.remove(key); - - plid = doGetPlidFromPortletId( - groupId, privateLayout, portletId); - - if (plid != LayoutConstants.DEFAULT_PLID) { - _plidToPortletIdMap.put(key, plid); - } - } - } - - return plid; - } - - public long getPlidFromPortletId(long groupId, String portletId) - throws PortalException, SystemException { - - long plid = getPlidFromPortletId(groupId, false, portletId); - - if (plid == LayoutConstants.DEFAULT_PLID) { - plid = getPlidFromPortletId(groupId, true, portletId); - } - - if (plid == LayoutConstants.DEFAULT_PLID) { - if (_log.isDebugEnabled()) { - _log.debug( - "Portlet " + portletId + - " does not exist on a page in group " + groupId); - } - } - - return plid; - } - - public String getPortalLibDir() { - return PropsValues.LIFERAY_LIB_PORTAL_DIR; - } - - /** - * @deprecated {@link #getPortalPort(boolean)} - */ - public int getPortalPort() { - return _portalPort.get(); - } - - public int getPortalPort(boolean secure) { - if (secure) { - return _securePortalPort.get(); - } - else { - return _portalPort.get(); - } - } - - public Properties getPortalProperties() { - return PropsUtil.getProperties(); - } - - public String getPortalURL(HttpServletRequest request) { - return getPortalURL(request, isSecure(request)); - } - - public String getPortalURL(HttpServletRequest request, boolean secure) { - return getPortalURL( - request.getServerName(), request.getServerPort(), secure); - } - - public String getPortalURL(Layout layout, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - String serverName = themeDisplay.getServerName(); - - if (layout == null) { - layout = themeDisplay.getLayout(); - } - - if (layout != null) { - LayoutSet layoutSet = layout.getLayoutSet(); - - String virtualHostname = layoutSet.getVirtualHostname(); - - if (Validator.isNotNull(virtualHostname)) { - serverName = virtualHostname; - } - } - - return getPortalURL( - serverName, themeDisplay.getServerPort(), themeDisplay.isSecure()); - } - - public String getPortalURL(PortletRequest portletRequest) { - return getPortalURL(portletRequest, portletRequest.isSecure()); - } - - public String getPortalURL(PortletRequest portletRequest, boolean secure) { - return getPortalURL( - portletRequest.getServerName(), portletRequest.getServerPort(), - secure); - } - - public String getPortalURL( - String serverName, int serverPort, boolean secure) { - - StringBundler sb = new StringBundler(); - - if (secure || Http.HTTPS.equals(PropsValues.WEB_SERVER_PROTOCOL)) { - sb.append(Http.HTTPS_WITH_SLASH); - } - else { - sb.append(Http.HTTP_WITH_SLASH); - } - - if (Validator.isNull(PropsValues.WEB_SERVER_HOST)) { - sb.append(serverName); - } - else { - sb.append(PropsValues.WEB_SERVER_HOST); - } - - if (!secure) { - if (PropsValues.WEB_SERVER_HTTP_PORT == -1) { - if ((serverPort != Http.HTTP_PORT) && - (serverPort != Http.HTTPS_PORT)) { - - sb.append(StringPool.COLON); - sb.append(serverPort); - } - } - else { - if (PropsValues.WEB_SERVER_HTTP_PORT != Http.HTTP_PORT) { - sb.append(StringPool.COLON); - sb.append(PropsValues.WEB_SERVER_HTTP_PORT); - } - } - } - - if (secure) { - if (PropsValues.WEB_SERVER_HTTPS_PORT == -1) { - if ((serverPort != Http.HTTP_PORT) && - (serverPort != Http.HTTPS_PORT)) { - - sb.append(StringPool.COLON); - sb.append(serverPort); - } - } - else { - if (PropsValues.WEB_SERVER_HTTPS_PORT != Http.HTTPS_PORT) { - sb.append(StringPool.COLON); - sb.append(PropsValues.WEB_SERVER_HTTPS_PORT); - } - } - } - - return sb.toString(); - } - - public String getPortalURL(ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getPortalURL(null, themeDisplay); - } - - public String getPortalWebDir() { - return PropsValues.LIFERAY_WEB_PORTAL_DIR; - } - - public Set getPortletAddDefaultResourceCheckWhitelist() { - return _portletAddDefaultResourceCheckWhitelist; - } - - public Set getPortletAddDefaultResourceCheckWhitelistActions() { - return _portletAddDefaultResourceCheckWhitelistActions; - } - - /** - * @deprecated {@link #getPortletBreadcrumbs(HttpServletRequest)} - */ - public List getPortletBreadcrumbList( - HttpServletRequest request) { - - return getPortletBreadcrumbs(request); - } - - public List getPortletBreadcrumbs( - HttpServletRequest request) { - - return (List)request.getAttribute( - WebKeys.PORTLET_BREADCRUMBS); - } - - public String getPortletDescription( - Portlet portlet, ServletContext servletContext, Locale locale) { - - PortletConfig portletConfig = PortletConfigFactoryUtil.create( - portlet, servletContext); - - ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale); - - return resourceBundle.getString( - JavaConstants.JAVAX_PORTLET_DESCRIPTION); - } - - public String getPortletDescription(Portlet portlet, User user) { - return getPortletDescription(portlet.getPortletId(), user); - } - - public String getPortletDescription(String portletId, Locale locale) { - return LanguageUtil.get( - locale, - JavaConstants.JAVAX_PORTLET_DESCRIPTION.concat( - StringPool.PERIOD).concat(portletId)); - } - - public String getPortletDescription(String portletId, String languageId) { - Locale locale = LocaleUtil.fromLanguageId(languageId); - - return getPortletDescription(portletId, locale); - } - - public String getPortletDescription(String portletId, User user) { - return LanguageUtil.get( - user.getLocale(), - JavaConstants.JAVAX_PORTLET_DESCRIPTION.concat( - StringPool.PERIOD).concat(portletId)); - } - - public Object[] getPortletFriendlyURLMapper( - long groupId, boolean privateLayout, String url, - Map params, Map requestContext) - throws PortalException, SystemException { - - boolean foundFriendlyURLMapper = false; - - String friendlyURL = url; - String queryString = StringPool.BLANK; - - List portlets = - PortletLocalServiceUtil.getFriendlyURLMapperPortlets(); - - Iterator itr = portlets.iterator(); - - while (itr.hasNext()) { - Portlet portlet = itr.next(); - - FriendlyURLMapper friendlyURLMapper = - portlet.getFriendlyURLMapperInstance(); - - if (url.endsWith( - StringPool.SLASH + friendlyURLMapper.getMapping())) { - - url += StringPool.SLASH; - } - - int pos = -1; - - if (friendlyURLMapper.isCheckMappingWithPrefix()) { - pos = url.indexOf( - FRIENDLY_URL_SEPARATOR + friendlyURLMapper.getMapping() + - StringPool.SLASH); - } - else { - pos = url.indexOf( - StringPool.SLASH + friendlyURLMapper.getMapping() + - StringPool.SLASH); - } - - if (pos != -1) { - foundFriendlyURLMapper = true; - - friendlyURL = url.substring(0, pos); - - InheritableMap actualParams = - new InheritableMap(); - - if (params != null) { - actualParams.setParentMap(params); - } - - Map prpIdentifiers = - new HashMap(); - - Set publicRenderParameters = - portlet.getPublicRenderParameters(); - - for (PublicRenderParameter publicRenderParameter : - publicRenderParameters) { - - QName qName = publicRenderParameter.getQName(); - - String publicRenderParameterIdentifier = - qName.getLocalPart(); - String publicRenderParameterName = - PortletQNameUtil.getPublicRenderParameterName(qName); - - prpIdentifiers.put( - publicRenderParameterIdentifier, - publicRenderParameterName); - } - - FriendlyURLMapperThreadLocal.setPRPIdentifiers(prpIdentifiers); - - if (friendlyURLMapper.isCheckMappingWithPrefix()) { - friendlyURLMapper.populateParams( - url.substring(pos + 2), actualParams, - requestContext); - } - else { - friendlyURLMapper.populateParams( - url.substring(pos), actualParams, requestContext); - } - - queryString = - StringPool.AMPERSAND + - HttpUtil.parameterMapToString(actualParams, false); - - break; - } - } - - if (!foundFriendlyURLMapper) { - int x = url.indexOf(FRIENDLY_URL_SEPARATOR); - - if (x != -1) { - int y = url.indexOf(CharPool.SLASH, x + 3); - - if (y == -1) { - y = url.length(); - } - - String ppid = url.substring(x + 3, y); - - if (Validator.isNotNull(ppid)) { - friendlyURL = url.substring(0, x); - - Map actualParams = null; - - if (params != null) { - actualParams = new HashMap(params); - } - else { - actualParams = new HashMap(); - } - - actualParams.put("p_p_id", new String[] {ppid}); - actualParams.put("p_p_lifecycle", new String[] {"0"}); - actualParams.put( - "p_p_state", - new String[] {WindowState.MAXIMIZED.toString()}); - actualParams.put( - "p_p_mode", new String[] {PortletMode.VIEW.toString()}); - - queryString = - StringPool.AMPERSAND + - HttpUtil.parameterMapToString(actualParams, false); - } - } - } - - friendlyURL = StringUtil.replace( - friendlyURL, StringPool.DOUBLE_SLASH, StringPool.SLASH); - - if (friendlyURL.endsWith(StringPool.SLASH)) { - friendlyURL = friendlyURL.substring(0, friendlyURL.length() - 1); - } - - Layout layout = LayoutLocalServiceUtil.getFriendlyURLLayout( - groupId, privateLayout, friendlyURL); - - return new Object[] {layout, queryString}; - } - - public String getPortletId(HttpServletRequest request) { - PortletConfigImpl portletConfigImpl = - (PortletConfigImpl)request.getAttribute( - JavaConstants.JAVAX_PORTLET_CONFIG); - - if (portletConfigImpl != null) { - return portletConfigImpl.getPortletId(); - } - else { - return null; - } - } - - public String getPortletId(PortletRequest portletRequest) { - PortletConfigImpl portletConfigImpl = - (PortletConfigImpl)portletRequest.getAttribute( - JavaConstants.JAVAX_PORTLET_CONFIG); - - if (portletConfigImpl != null) { - return portletConfigImpl.getPortletId(); - } - else { - return null; - } - } - - public String getPortletLongTitle(Portlet portlet, Locale locale) { - return getPortletLongTitle(portlet.getPortletId(), locale); - } - - public String getPortletLongTitle( - Portlet portlet, ServletContext servletContext, Locale locale) { - - PortletConfig portletConfig = PortletConfigFactoryUtil.create( - portlet, servletContext); - - ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale); - - try { - String portletLongTitle = resourceBundle.getString( - JavaConstants.JAVAX_PORTLET_LONG_TITLE); - - if (portletLongTitle.startsWith( - JavaConstants.JAVAX_PORTLET_LONG_TITLE)) { - - portletLongTitle = getPortletTitle( - portlet, servletContext, locale); - } - - return portletLongTitle; - } - catch (Exception e) { - return getPortletTitle(portlet, servletContext, locale); - } - } - - public String getPortletLongTitle(Portlet portlet, String languageId) { - return getPortletLongTitle(portlet.getPortletId(), languageId); - } - - public String getPortletLongTitle(Portlet portlet, User user) { - return getPortletLongTitle(portlet.getPortletId(), user); - } - - public String getPortletLongTitle(String portletId, Locale locale) { - String portletLongTitle = LanguageUtil.get( - locale, - JavaConstants.JAVAX_PORTLET_LONG_TITLE.concat( - StringPool.PERIOD).concat(portletId), - StringPool.BLANK); - - if (Validator.isNull(portletLongTitle)) { - portletLongTitle = getPortletTitle(portletId, locale); - } - - return portletLongTitle; - } - - public String getPortletLongTitle(String portletId, String languageId) { - Locale locale = LocaleUtil.fromLanguageId(languageId); - - return getPortletLongTitle(portletId, locale); - } - - public String getPortletLongTitle(String portletId, User user) { - return getPortletLongTitle(portletId, user.getLocale()); - } - - public String getPortletNamespace(String portletId) { - return StringPool.UNDERLINE.concat(portletId).concat( - StringPool.UNDERLINE); - } - - public String getPortletTitle(Portlet portlet, Locale locale) { - return getPortletTitle(portlet.getPortletId(), locale); - } - - public String getPortletTitle( - Portlet portlet, ServletContext servletContext, Locale locale) { - - PortletConfig portletConfig = PortletConfigFactoryUtil.create( - portlet, servletContext); - - ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale); - - return resourceBundle.getString(JavaConstants.JAVAX_PORTLET_TITLE); - } - - public String getPortletTitle(Portlet portlet, String languageId) { - return getPortletTitle(portlet.getPortletId(), languageId); - } - - public String getPortletTitle(Portlet portlet, User user) { - return getPortletTitle(portlet.getPortletId(), user); - } - - public String getPortletTitle(RenderResponse renderResponse) { - PortletResponseImpl portletResponseImpl = - PortletResponseImpl.getPortletResponseImpl(renderResponse); - - return ((RenderResponseImpl)portletResponseImpl).getTitle(); - } - - public String getPortletTitle(String portletId, Locale locale) { - return LanguageUtil.get( - locale, - JavaConstants.JAVAX_PORTLET_TITLE.concat(StringPool.PERIOD).concat( - portletId)); - } - - public String getPortletTitle(String portletId, String languageId) { - Locale locale = LocaleUtil.fromLanguageId(languageId); - - return getPortletTitle(portletId, locale); - } - - public String getPortletTitle(String portletId, User user) { - return LanguageUtil.get( - user.getLocale(), - JavaConstants.JAVAX_PORTLET_TITLE.concat(StringPool.PERIOD).concat( - portletId)); - } - - public String getPortletXmlFileName() throws SystemException { - if (PrefsPropsUtil.getBoolean( - PropsKeys.AUTO_DEPLOY_CUSTOM_PORTLET_XML, - PropsValues.AUTO_DEPLOY_CUSTOM_PORTLET_XML)) { - - return PORTLET_XML_FILE_NAME_CUSTOM; - } - else { - return PORTLET_XML_FILE_NAME_STANDARD; - } - } - - public PortletPreferences getPreferences(HttpServletRequest request) { - RenderRequest renderRequest = (RenderRequest)request.getAttribute( - JavaConstants.JAVAX_PORTLET_REQUEST); - - PortletPreferences portletPreferences = null; - - if (renderRequest != null) { - PortletPreferencesWrapper portletPreferencesWrapper = - (PortletPreferencesWrapper)renderRequest.getPreferences(); - - portletPreferences = - portletPreferencesWrapper.getPortletPreferencesImpl(); - } - - return portletPreferences; - } - - public PreferencesValidator getPreferencesValidator(Portlet portlet) { - PortletBag portletBag = PortletBagPool.get(portlet.getRootPortletId()); - - return portletBag.getPreferencesValidatorInstance(); - } - - public String getRelativeHomeURL(HttpServletRequest request) - throws PortalException, SystemException { - - Company company = getCompany(request); - - String homeURL = company.getHomeURL(); - - if (Validator.isNull(homeURL)) { - homeURL = PropsValues.COMPANY_DEFAULT_HOME_URL; - } - - return homeURL; - } - - public long getScopeGroupId(HttpServletRequest request) - throws PortalException, SystemException { - - String portletId = getPortletId(request); - - return getScopeGroupId(request, portletId); - } - - public long getScopeGroupId(HttpServletRequest request, String portletId) - throws PortalException, SystemException { - - return getScopeGroupId(request, portletId, false); - } - - public long getScopeGroupId( - HttpServletRequest request, String portletId, - boolean checkStagingGroup) - throws PortalException, SystemException { - - Layout layout = (Layout)request.getAttribute(WebKeys.LAYOUT); - - long scopeGroupId = 0; - - if (layout != null) { - Group group = layout.getGroup(); - - if (group.isControlPanel()) { - long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId"); - - Group doAsGroup = GroupLocalServiceUtil.fetchGroup(doAsGroupId); - - if ((doAsGroupId <= 0) || (doAsGroup == null)) { - doAsGroupId = getDefaultScopeGroupId(group.getCompanyId()); - } - - if (doAsGroupId > 0) { - scopeGroupId = doAsGroupId; - } - - group = GroupLocalServiceUtil.fetchGroup(scopeGroupId); - - if ((group != null) && group.hasStagingGroup()) { - try { - Group stagingGroup = group.getStagingGroup(); - - scopeGroupId = stagingGroup.getGroupId(); - } - catch (Exception e) { - } - } - } - - if ((portletId != null) && - (group.isStaged() || group.isStagingGroup())) { - - Group liveGroup = group; - - if (group.isStagingGroup()) { - liveGroup = group.getLiveGroup(); - } - - if (liveGroup.isStaged() && - !liveGroup.isStagedPortlet(portletId)) { - - Layout liveGroupLayout = - LayoutLocalServiceUtil.fetchLayoutByUuidAndGroupId( - layout.getUuid(), liveGroup.getGroupId()); - - if ((liveGroupLayout != null) && - liveGroupLayout.hasScopeGroup()) { - - scopeGroupId = getScopeGroupId( - liveGroupLayout, portletId); - } - else if (checkStagingGroup && - !liveGroup.isStagedRemotely()) { - - Group stagingGroup = liveGroup.getStagingGroup(); - - scopeGroupId = stagingGroup.getGroupId(); - } - else { - scopeGroupId = liveGroup.getGroupId(); - } - } - } - } - - if (scopeGroupId <= 0) { - scopeGroupId = getScopeGroupId(layout, portletId); - } - - return scopeGroupId; - } - - public long getScopeGroupId(Layout layout) { - if (layout == null) { - return 0; - } - else { - return layout.getGroupId(); - } - } - - public long getScopeGroupId(Layout layout, String portletId) { - if (layout == null) { - return 0; - } - - if (Validator.isNull(portletId)) { - return layout.getGroupId(); - } - - boolean strict = PortletPreferencesThreadLocal.isStrict(); - - PortletPreferencesThreadLocal.setStrict(true); - - try { - PortletPreferences portletSetup = - PortletPreferencesFactoryUtil.getLayoutPortletSetup( - layout, portletId); - - String scopeType = GetterUtil.getString( - portletSetup.getValue("lfrScopeType", null)); - - if (Validator.isNull(scopeType)) { - return layout.getGroupId(); - } - - if (scopeType.equals("company")) { - Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( - layout.getCompanyId()); - - return companyGroup.getGroupId(); - } - else { - String scopeLayoutUuid = GetterUtil.getString( - portletSetup.getValue("lfrScopeLayoutUuid", null)); - - Layout scopeLayout = - LayoutLocalServiceUtil.getLayoutByUuidAndGroupId( - scopeLayoutUuid, layout.getGroupId()); - - Group scopeGroup = scopeLayout.getScopeGroup(); - - return scopeGroup.getGroupId(); - } - } - catch (Exception e) { - return layout.getGroupId(); - } - finally { - PortletPreferencesThreadLocal.setStrict(strict); - } - } - - public long getScopeGroupId(long plid) { - Layout layout = null; - - try { - layout = LayoutLocalServiceUtil.getLayout(plid); - } - catch (Exception e) { - } - - return getScopeGroupId(layout); - } - - public long getScopeGroupId(PortletRequest portletRequest) - throws PortalException, SystemException { - - return getScopeGroupId(getHttpServletRequest(portletRequest)); - } - - public User getSelectedUser(HttpServletRequest request) - throws PortalException, SystemException { - - return getSelectedUser(request, true); - } - - public User getSelectedUser( - HttpServletRequest request, boolean checkPermission) - throws PortalException, SystemException { - - long userId = ParamUtil.getLong(request, "p_u_i_d"); - - User user = null; - - try { - if (checkPermission) { - user = UserServiceUtil.getUserById(userId); - } - else { - user = UserLocalServiceUtil.getUserById(userId); - } - } - catch (NoSuchUserException nsue) { - } - - return user; - } - - public User getSelectedUser(PortletRequest portletRequest) - throws PortalException, SystemException { - - return getSelectedUser(portletRequest, true); - } - - public User getSelectedUser( - PortletRequest portletRequest, boolean checkPermission) - throws PortalException, SystemException { - - return getSelectedUser( - getHttpServletRequest(portletRequest), checkPermission); - } - - public ServletContext getServletContext( - Portlet portlet, ServletContext servletContext) { - - PortletConfig portletConfig = PortletConfigFactoryUtil.create( - portlet, servletContext); - - PortletContextImpl portletContextImpl = - (PortletContextImpl)portletConfig.getPortletContext(); - - return portletContextImpl.getServletContext(); - } - - public String getSiteLoginURL(ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - if (Validator.isNull(PropsValues.AUTH_LOGIN_SITE_URL)) { - return null; - } - - List layouts = themeDisplay.getUnfilteredLayouts(); - - if (layouts == null) { - return null; - } - - for (Layout layout : layouts) { - String friendlyURL = layout.getFriendlyURL(); - - if (friendlyURL.equals(PropsValues.AUTH_LOGIN_SITE_URL)) { - if (themeDisplay.getLayout() == null) { - break; - } - - String layoutSetFriendlyURL = getLayoutSetFriendlyURL( - layout.getLayoutSet(), themeDisplay); - - return layoutSetFriendlyURL + PropsValues.AUTH_LOGIN_SITE_URL; - } - } - - return null; - } - - public String getStaticResourceURL(HttpServletRequest request, String uri) { - return getStaticResourceURL(request, uri, null, 0); - } - - public String getStaticResourceURL( - HttpServletRequest request, String uri, long timestamp) { - - return getStaticResourceURL(request, uri, null, timestamp); - } - - public String getStaticResourceURL( - HttpServletRequest request, String uri, String queryString) { - - return getStaticResourceURL(request, uri, queryString, 0); - } - - public String getStaticResourceURL( - HttpServletRequest request, String uri, String queryString, - long timestamp) { - - if (uri.indexOf(CharPool.QUESTION) != -1) { - return uri; - } - - if (uri.startsWith(StringPool.DOUBLE_SLASH)) { - uri = uri.substring(1); - } - - ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( - WebKeys.THEME_DISPLAY); - - Theme theme = themeDisplay.getTheme(); - ColorScheme colorScheme = themeDisplay.getColorScheme(); - - Map parameterMap = null; - - if (Validator.isNotNull(queryString)) { - parameterMap = HttpUtil.getParameterMap(queryString); - } - - StringBundler sb = new StringBundler(); - - // URI - - sb.append(uri); - sb.append(StringPool.QUESTION); - - // Browser id - - if ((parameterMap == null) || - (!parameterMap.containsKey("browserId"))) { - - sb.append("&browserId="); - sb.append(BrowserSnifferUtil.getBrowserId(request)); - } - - // Theme and color scheme - - if ((uri.endsWith(".css") || uri.endsWith(".jsp")) && - ((parameterMap == null) || !parameterMap.containsKey("themeId"))) { - - sb.append("&themeId="); - sb.append(theme.getThemeId()); - } - - if (uri.endsWith(".jsp") && - ((parameterMap == null) || - !parameterMap.containsKey("colorSchemeId"))) { - - sb.append("&colorSchemeId="); - sb.append(colorScheme.getColorSchemeId()); - } - - // Minifier - - if ((parameterMap == null) || - (!parameterMap.containsKey("minifierType"))) { - - String minifierType = StringPool.BLANK; - - if (uri.endsWith(".css") || uri.endsWith("css.jsp") || - uri.matches(".*/css/.*\\.jsp")) { - - if (themeDisplay.isThemeCssFastLoad()) { - minifierType = "css"; - } - } - else if (themeDisplay.isThemeJsFastLoad()) { - minifierType = "js"; - } - - if (Validator.isNotNull(minifierType)) { - sb.append("&minifierType="); - sb.append(minifierType); - } - } - - // Query string - - if (Validator.isNotNull(queryString)) { - if (!queryString.startsWith(StringPool.AMPERSAND)) { - sb.append(StringPool.AMPERSAND); - } - - sb.append(queryString); - } - - // Language id - - sb.append("&languageId="); - sb.append(themeDisplay.getLanguageId()); - - // Build number - - sb.append("&b="); - sb.append(ReleaseInfo.getBuildNumber()); - - // Timestamp - - if ((parameterMap == null) || !parameterMap.containsKey("t")) { - if ((timestamp == 0) && uri.startsWith(StrutsUtil.TEXT_HTML_DIR)) { - ServletContext servletContext = - (ServletContext)request.getAttribute(WebKeys.CTX); - - timestamp = FileTimestampUtil.getTimestamp(servletContext, uri); - } - - if (timestamp == 0) { - timestamp = theme.getTimestamp(); - } - - sb.append("&t="); - sb.append(timestamp); - } - - String url = sb.toString(); - - url = StringUtil.replace(url, "?&", StringPool.QUESTION); - - return url; - } - - public String getStrutsAction(HttpServletRequest request) { - String strutsAction = ParamUtil.getString(request, "struts_action"); - - if (Validator.isNotNull(strutsAction)) { - - // This method should only return a Struts action if you're dealing - // with a regular HTTP servlet request, not a portlet HTTP servlet - // request. - - return StringPool.BLANK; - } - - return getPortletParam(request, "struts_action"); - } - - public String[] getSystemGroups() { - return _allSystemGroups; - } - - public String[] getSystemOrganizationRoles() { - return _allSystemOrganizationRoles; - } - - public String[] getSystemRoles() { - return _allSystemRoles; - } - - public String[] getSystemSiteRoles() { - return _allSystemSiteRoles; - } - - public UploadPortletRequest getUploadPortletRequest( - PortletRequest portletRequest) { - - PortletRequestImpl portletRequestImpl = - (PortletRequestImpl)portletRequest; - - DynamicServletRequest dynamicRequest = - (DynamicServletRequest)portletRequestImpl.getHttpServletRequest(); - - HttpServletRequestWrapper requestWrapper = - (HttpServletRequestWrapper)dynamicRequest.getRequest(); - - UploadServletRequest uploadServletRequest = getUploadServletRequest( - requestWrapper); - - return new UploadPortletRequestImpl( - uploadServletRequest, - getPortletNamespace(portletRequestImpl.getPortletName())); - } - - public UploadServletRequest getUploadServletRequest( - HttpServletRequest request) { - - HttpServletRequestWrapper requestWrapper = null; - - if (request instanceof HttpServletRequestWrapper) { - requestWrapper = (HttpServletRequestWrapper)request; - } - - UploadServletRequest uploadServletRequest = null; - - while (uploadServletRequest == null) { - - // Find the underlying UploadServletRequest wrapper. For example, - // WebSphere wraps all requests with ProtectedServletRequest. - - if (requestWrapper instanceof UploadServletRequest) { - uploadServletRequest = (UploadServletRequest)requestWrapper; - } - else { - HttpServletRequest parentRequest = - (HttpServletRequest)requestWrapper.getRequest(); - - if (!(parentRequest instanceof HttpServletRequestWrapper)) { - - // This block should never be reached unless this method is - // called from a hot deployable portlet. See LayoutAction. - - uploadServletRequest = new UploadServletRequestImpl( - parentRequest); - - break; - } - else { - requestWrapper = (HttpServletRequestWrapper)parentRequest; - } - } - } - - return uploadServletRequest; - } - - public Date getUptime() { - return _upTime; - } - - public String getURLWithSessionId(String url, String sessionId) { - if (!PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID) { - return url; - } - - if (Validator.isNull(url)) { - return url; - } - - // LEP-4787 - - int x = url.indexOf(CharPool.SEMICOLON); - - if (x != -1) { - return url; - } - - x = url.indexOf(CharPool.QUESTION); - - if (x != -1) { - StringBundler sb = new StringBundler(4); - - sb.append(url.substring(0, x)); - sb.append(_JSESSIONID); - sb.append(sessionId); - sb.append(url.substring(x)); - - return sb.toString(); - } - - // In IE6, http://www.abc.com;jsessionid=XYZ does not work, but - // http://www.abc.com/;jsessionid=XYZ does work. - - x = url.indexOf(StringPool.DOUBLE_SLASH); - - StringBundler sb = new StringBundler(4); - - sb.append(url); - - if (x != -1) { - int y = url.lastIndexOf(CharPool.SLASH); - - if (x + 1 == y) { - sb.append(StringPool.SLASH); - } - } - - sb.append(_JSESSIONID); - sb.append(sessionId); - - return sb.toString(); - } - - public User getUser(HttpServletRequest request) - throws PortalException, SystemException { - - User user = (User)request.getAttribute(WebKeys.USER); - - if (user != null) { - return user; - } - - long userId = getUserId(request); - - if (userId <= 0) { - - // Portlet WARs may have the correct remote user and not have the - // correct user id because the user id is saved in the session - // and may not be accessible by the portlet WAR's session. This - // behavior is inconsistent across different application servers. - - String remoteUser = request.getRemoteUser(); - - if (remoteUser == null) { - return null; - } - - userId = GetterUtil.getLong(remoteUser); - } - - user = UserLocalServiceUtil.getUserById(userId); - - request.setAttribute(WebKeys.USER, user); - - return user; - } - - public User getUser(PortletRequest portletRequest) - throws PortalException, SystemException { - - return getUser(getHttpServletRequest(portletRequest)); - } - - public String getUserEmailAddress(long userId) throws SystemException { - try { - User user = UserLocalServiceUtil.getUserById(userId); - - return user.getEmailAddress(); - } - catch (PortalException pe) { - return StringPool.BLANK; - } - } - - public long getUserId(HttpServletRequest request) { - Long userIdObj = (Long)request.getAttribute(WebKeys.USER_ID); - - if (userIdObj != null) { - return userIdObj.longValue(); - } - - String path = GetterUtil.getString(request.getPathInfo()); - String strutsAction = getStrutsAction(request); - String actionName = getPortletParam(request, "actionName"); - - boolean alwaysAllowDoAsUser = false; - - if (path.equals("/portal/session_click") || - strutsAction.equals("/document_library/edit_file_entry") || - strutsAction.equals("/document_library_display/edit_file_entry") || - strutsAction.equals("/image_gallery_display/edit_file_entry") || - strutsAction.equals("/image_gallery_display/edit_image") || - strutsAction.equals("/wiki/edit_page_attachment") || - strutsAction.equals("/wiki_admin/edit_page_attachment") || - actionName.equals("addFile")) { - - try { - alwaysAllowDoAsUser = isAlwaysAllowDoAsUser(request); - } - catch (Exception e) { - _log.error(e, e); - } - } - - if ((!PropsValues.PORTAL_JAAS_ENABLE && - PropsValues.PORTAL_IMPERSONATION_ENABLE) || - (alwaysAllowDoAsUser)) { - - String doAsUserIdString = ParamUtil.getString( - request, "doAsUserId"); - - try { - long doAsUserId = getDoAsUserId( - request, doAsUserIdString, alwaysAllowDoAsUser); - - if (doAsUserId > 0) { - if (_log.isDebugEnabled()) { - _log.debug("Impersonating user " + doAsUserId); - } - - return doAsUserId; - } - } - catch (Exception e) { - _log.error("Unable to impersonate user " + doAsUserIdString, e); - } - } - - HttpSession session = request.getSession(); - - String jRemoteUser = null; - - if (PropsValues.PORTAL_JAAS_ENABLE) { - jRemoteUser = (String)session.getAttribute("j_remoteuser"); - } - - if (Validator.isNotNull(jRemoteUser)) { - userIdObj = GetterUtil.getLong(jRemoteUser); - } - else { - userIdObj = (Long)session.getAttribute(WebKeys.USER_ID); - } - - if (userIdObj != null) { - request.setAttribute(WebKeys.USER_ID, userIdObj); - - return userIdObj.longValue(); - } - else { - return 0; - } - } - - public long getUserId(PortletRequest portletRequest) { - return getUserId(getHttpServletRequest(portletRequest)); - } - - public String getUserName(long userId, String defaultUserName) { - return getUserName( - userId, defaultUserName, UserAttributes.USER_NAME_FULL); - } - - public String getUserName( - long userId, String defaultUserName, HttpServletRequest request) { - - return getUserName( - userId, defaultUserName, UserAttributes.USER_NAME_FULL, request); - } - - public String getUserName( - long userId, String defaultUserName, String userAttribute) { - - return getUserName(userId, defaultUserName, userAttribute, null); - } - - public String getUserName( - long userId, String defaultUserName, String userAttribute, - HttpServletRequest request) { - - String userName = defaultUserName; - - try { - User user = UserLocalServiceUtil.getUserById(userId); - - if (userAttribute.equals(UserAttributes.USER_NAME_FULL)) { - userName = user.getFullName(); - } - else { - userName = user.getScreenName(); - } - - if (request != null) { - Layout layout = (Layout)request.getAttribute(WebKeys.LAYOUT); - - PortletURL portletURL = new PortletURLImpl( - request, PortletKeys.DIRECTORY, layout.getPlid(), - PortletRequest.RENDER_PHASE); - - portletURL.setWindowState(WindowState.MAXIMIZED); - portletURL.setPortletMode(PortletMode.VIEW); - - portletURL.setParameter( - "struts_action", "/directory/view_user"); - portletURL.setParameter( - "p_u_i_d", String.valueOf(user.getUserId())); - - userName = - "" + - HtmlUtil.escape(userName) + ""; - } - } - catch (Exception e) { - } - - return userName; - } - - public String getUserPassword(HttpServletRequest request) { - HttpSession session = request.getSession(); - - return getUserPassword(session); - } - - public String getUserPassword(HttpSession session) { - return (String)session.getAttribute(WebKeys.USER_PASSWORD); - } - - public String getUserPassword(PortletRequest portletRequest) { - return getUserPassword(getHttpServletRequest(portletRequest)); - } - - public String getUserValue(long userId, String param, String defaultValue) - throws SystemException { - - if (Validator.isNotNull(defaultValue)) { - return defaultValue; - } - else { - try { - User user = UserLocalServiceUtil.getUserById(userId); - - return BeanPropertiesUtil.getString(user, param, defaultValue); - } - catch (PortalException pe) { - return StringPool.BLANK; - } - } - } - - public long getValidUserId(long companyId, long userId) - throws PortalException, SystemException { - - try { - User user = UserLocalServiceUtil.getUser(userId); - - if (user.getCompanyId() == companyId) { - return user.getUserId(); - } - else { - return userId; - } - } - catch (NoSuchUserException nsue) { - return UserLocalServiceUtil.getDefaultUserId(companyId); - } - } - - public String getVirtualLayoutActualURL( - long groupId, boolean privateLayout, String mainPath, - String friendlyURL, Map params, - Map requestContext) - throws PortalException, SystemException { - - // Group friendly URL - - String groupFriendlyURL = null; - - int pos = friendlyURL.indexOf(CharPool.SLASH, 3); - - if (pos != -1) { - groupFriendlyURL = friendlyURL.substring(2, pos); - } - - if (Validator.isNull(groupFriendlyURL)) { - return mainPath; - } - - HttpServletRequest request = (HttpServletRequest)requestContext.get( - "request"); - - long companyId = PortalInstances.getCompanyId(request); - - Group group = GroupLocalServiceUtil.fetchFriendlyURLGroup( - companyId, groupFriendlyURL); - - if (group == null) { - return mainPath; - } - - // Layout friendly URL - - String layoutFriendlyURL = null; - - if ((pos != -1) && ((pos + 1) != friendlyURL.length())) { - layoutFriendlyURL = friendlyURL.substring( - pos, friendlyURL.length()); - } - - if (Validator.isNull(layoutFriendlyURL)) { - return mainPath; - } - - String actualURL = getActualURL( - group.getGroupId(), privateLayout, mainPath, layoutFriendlyURL, - params, requestContext); - - return HttpUtil.addParameter( - HttpUtil.removeParameter(actualURL, "p_v_l_s_g_id"), "p_v_l_s_g_id", - groupId); - } - - public String getWidgetURL(Portlet portlet, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getServletURL( - portlet, PropsValues.WIDGET_SERVLET_MAPPING, themeDisplay); - } - - public void initCustomSQL() { - _customSqlKeys = new String[] { - "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.GROUP$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.LAYOUT$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.ORGANIZATION$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.ROLE$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.USER$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.USERGROUP$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.BLOGS.MODEL.BLOGSENTRY$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.BOOKMARKS.MODEL." + - "BOOKMARKSENTRY$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.CALENDAR.MODEL.CALEVENT$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.DOCUMENTLIBRARY.MODEL." + - "DLFILEENTRY$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.MESSAGEBOARDS.MODEL." + - "MBMESSAGE$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.MESSAGEBOARDS.MODEL." + - "MBTHREAD$]", - "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.WIKI.MODEL.WIKIPAGE$]", - "[$RESOURCE_SCOPE_COMPANY$]", - "[$RESOURCE_SCOPE_GROUP$]", - "[$RESOURCE_SCOPE_GROUP_TEMPLATE$]", - "[$RESOURCE_SCOPE_INDIVIDUAL$]", - "[$SOCIAL_RELATION_TYPE_BI_COWORKER$]", - "[$SOCIAL_RELATION_TYPE_BI_FRIEND$]", - "[$SOCIAL_RELATION_TYPE_BI_ROMANTIC_PARTNER$]", - "[$SOCIAL_RELATION_TYPE_BI_SIBLING$]", - "[$SOCIAL_RELATION_TYPE_BI_SPOUSE$]", - "[$SOCIAL_RELATION_TYPE_UNI_CHILD$]", - "[$SOCIAL_RELATION_TYPE_UNI_ENEMY$]", - "[$SOCIAL_RELATION_TYPE_UNI_FOLLOWER$]", - "[$SOCIAL_RELATION_TYPE_UNI_PARENT$]", - "[$SOCIAL_RELATION_TYPE_UNI_SUBORDINATE$]", - "[$SOCIAL_RELATION_TYPE_UNI_SUPERVISOR$]", - "[$FALSE$]", - "[$TRUE$]" - }; - - DB db = DBFactoryUtil.getDB(); - - Object[] customSqlValues = new Object[] { - getClassNameId(Group.class), - getClassNameId(Layout.class), - getClassNameId(Organization.class), - getClassNameId(Role.class), - getClassNameId(User.class), - getClassNameId(UserGroup.class), - getClassNameId(BlogsEntry.class), - getClassNameId(BookmarksEntry.class), - getClassNameId(CalEvent.class), - getClassNameId(DLFileEntry.class), - getClassNameId(MBMessage.class), - getClassNameId(MBThread.class), - getClassNameId(WikiPage.class), - ResourceConstants.SCOPE_COMPANY, - ResourceConstants.SCOPE_GROUP, - ResourceConstants.SCOPE_GROUP_TEMPLATE, - ResourceConstants.SCOPE_INDIVIDUAL, - SocialRelationConstants.TYPE_BI_COWORKER, - SocialRelationConstants.TYPE_BI_FRIEND, - SocialRelationConstants.TYPE_BI_ROMANTIC_PARTNER, - SocialRelationConstants.TYPE_BI_SIBLING, - SocialRelationConstants.TYPE_BI_SPOUSE, - SocialRelationConstants.TYPE_UNI_CHILD, - SocialRelationConstants.TYPE_UNI_ENEMY, - SocialRelationConstants.TYPE_UNI_FOLLOWER, - SocialRelationConstants.TYPE_UNI_PARENT, - SocialRelationConstants.TYPE_UNI_SUBORDINATE, - SocialRelationConstants.TYPE_UNI_SUPERVISOR, - db.getTemplateFalse(), - db.getTemplateTrue() - }; - - _customSqlValues = ArrayUtil.toStringArray(customSqlValues); - } - - public boolean isAllowAddPortletDefaultResource( - HttpServletRequest request, Portlet portlet) - throws PortalException, SystemException { - - ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( - WebKeys.THEME_DISPLAY); - - Layout layout = themeDisplay.getLayout(); - LayoutTypePortlet layoutTypePortlet = - themeDisplay.getLayoutTypePortlet(); - - String portletId = portlet.getPortletId(); - - Boolean renderPortletResource = (Boolean)request.getAttribute( - WebKeys.RENDER_PORTLET_RESOURCE); - - if (renderPortletResource != null) { - boolean runtimePortlet = renderPortletResource.booleanValue(); - - if (runtimePortlet) { - return true; - } - } - - if (layout.isTypePanel() && - isPanelSelectedPortlet(themeDisplay, portletId)) { - - return true; - } - - if (layout.isTypeControlPanel() && - isControlPanelPortlet(portletId, themeDisplay)) { - - return true; - } - - if (layout.isTypePortlet()) { - String checkPortletId = portletId; - - String outerPortletId = getOuterPortletId(request); - - if (outerPortletId != null) { - checkPortletId = outerPortletId; - } - - if (layoutTypePortlet.hasPortletId(checkPortletId)) { - return true; - } - } - - if (themeDisplay.isSignedIn() && - (portletId.equals(PortletKeys.LAYOUT_CONFIGURATION) || - portletId.equals(PortletKeys.LAYOUTS_ADMIN))) { - - PermissionChecker permissionChecker = - themeDisplay.getPermissionChecker(); - - Group group = layout.getGroup(); - - if (group.isSite()) { - if (LayoutPermissionUtil.contains( - permissionChecker, layout, ActionKeys.CUSTOMIZE) || - LayoutPermissionUtil.contains( - permissionChecker, layout, ActionKeys.UPDATE)) { - - return true; - } - } - - if (group.isCompany()) { - if (permissionChecker.isCompanyAdmin()) { - return true; - } - } - else if (group.isLayoutPrototype()) { - long layoutPrototypeId = group.getClassPK(); - - if (LayoutPrototypePermissionUtil.contains( - permissionChecker, layoutPrototypeId, - ActionKeys.UPDATE)) { - - return true; - } - } - else if (group.isLayoutSetPrototype()) { - long layoutSetPrototypeId = group.getClassPK(); - - if (LayoutSetPrototypePermissionUtil.contains( - permissionChecker, layoutSetPrototypeId, - ActionKeys.UPDATE)) { - - return true; - } - } - else if (group.isOrganization()) { - long organizationId = group.getOrganizationId(); - - if (OrganizationPermissionUtil.contains( - permissionChecker, organizationId, ActionKeys.UPDATE)) { - - return true; - } - } - else if (group.isUserGroup()) { - long scopeGroupId = themeDisplay.getScopeGroupId(); - - if (GroupPermissionUtil.contains( - permissionChecker, scopeGroupId, ActionKeys.UPDATE)) { - - return true; - } - } - else if (group.isUser()) { - return true; - } - } - - if (!portlet.isAddDefaultResource()) { - return false; - } - - if (!PropsValues.PORTLET_ADD_DEFAULT_RESOURCE_CHECK_ENABLED) { - return true; - } - - if (_portletAddDefaultResourceCheckWhitelist.contains(portletId)) { - return true; - } - - String strutsAction = ParamUtil.getString(request, "struts_action"); - - if (_portletAddDefaultResourceCheckWhitelistActions.contains( - strutsAction)) { - - return true; - } - - String requestPortletAuthenticationToken = ParamUtil.getString( - request, "p_p_auth"); - - if (Validator.isNull(requestPortletAuthenticationToken)) { - HttpServletRequest originalRequest = getOriginalServletRequest( - request); - - requestPortletAuthenticationToken = ParamUtil.getString( - originalRequest, "p_p_auth"); - } - - if (Validator.isNotNull(requestPortletAuthenticationToken)) { - String actualPortletAuthenticationToken = AuthTokenUtil.getToken( - request, layout.getPlid(), portletId); - - if (requestPortletAuthenticationToken.equals( - actualPortletAuthenticationToken)) { - - return true; - } - } - - return false; - } - - /** - * @deprecated As of 6.1, renamed to {@link #isGroupAdmin(User, long)} - */ - public boolean isCommunityAdmin(User user, long groupId) throws Exception { - return isGroupAdmin(user, groupId); - } - - /** - * @deprecated As of 6.1, renamed to {@link #isGroupOwner(User, long)} - */ - public boolean isCommunityOwner(User user, long groupId) throws Exception { - return isGroupOwner(user, groupId); - } - - public boolean isCompanyAdmin(User user) throws Exception { - PermissionChecker permissionChecker = - PermissionCheckerFactoryUtil.create(user, true); - - return permissionChecker.isCompanyAdmin(); - } - - public boolean isCompanyControlPanelPortlet( - String portletId, String category, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - PermissionChecker permissionChecker = - themeDisplay.getPermissionChecker(); - - if (permissionChecker.isCompanyAdmin()) { - return true; - } - - Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( - themeDisplay.getCompanyId()); - - themeDisplay.setScopeGroupId(companyGroup.getGroupId()); - - return isControlPanelPortlet(portletId, category, themeDisplay); - } - - public boolean isCompanyControlPanelPortlet( - String portletId, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - PermissionChecker permissionChecker = - themeDisplay.getPermissionChecker(); - - if (permissionChecker.isCompanyAdmin()) { - return true; - } - - Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( - themeDisplay.getCompanyId()); - - themeDisplay.setScopeGroupId(companyGroup.getGroupId()); - - return isControlPanelPortlet(portletId, themeDisplay); - } - - public boolean isCompanyControlPanelVisible(ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - PermissionChecker permissionChecker = - themeDisplay.getPermissionChecker(); - - if (permissionChecker.isCompanyAdmin()) { - return true; - } - - long scopeGroupId = themeDisplay.getScopeGroupId(); - - try { - Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( - themeDisplay.getCompanyId()); - - themeDisplay.setScopeGroupId(companyGroup.getGroupId()); - - List controlPanelPortlets = getControlPanelPortlets( - PortletCategoryKeys.CONTENT, themeDisplay); - - if (!controlPanelPortlets.isEmpty()) { - return true; - } - else { - return false; - } - } - finally { - themeDisplay.setScopeGroupId(scopeGroupId); - } - } - - public boolean isControlPanelPortlet( - String portletId, String category, ThemeDisplay themeDisplay) - throws SystemException { - - List portlets = getControlPanelPortlets( - category, themeDisplay); - - for (Portlet portlet : portlets) { - if (portlet.getPortletId().equals(portletId)) { - return true; - } - } - - return false; - } - - public boolean isControlPanelPortlet( - String portletId, ThemeDisplay themeDisplay) - throws SystemException { - - for (String category : PortletCategoryKeys.ALL) { - if (isControlPanelPortlet(portletId, category, themeDisplay)) { - return true; - } - } - - return false; - } - - public boolean isGroupAdmin(User user, long groupId) throws Exception { - PermissionChecker permissionChecker = - PermissionCheckerFactoryUtil.create(user, true); - - return permissionChecker.isGroupAdmin(groupId); - } - - public boolean isGroupOwner(User user, long groupId) throws Exception { - PermissionChecker permissionChecker = - PermissionCheckerFactoryUtil.create(user, true); - - return permissionChecker.isGroupOwner(groupId); - } - - public boolean isLayoutDescendant(Layout layout, long layoutId) - throws PortalException, SystemException { - - if (layout.getLayoutId() == layoutId) { - return true; - } - else { - for (Layout childLayout : layout.getChildren()) { - if (isLayoutDescendant(childLayout, layoutId)) { - return true; - } - } - - return false; - } - } - - public boolean isLayoutFirstPageable(Layout layout) { - LayoutSettings layoutSettings = LayoutSettings.getInstance(layout); - - return layoutSettings.isFirstPageable(); - } - - public boolean isLayoutFirstPageable(String type) { - LayoutSettings layoutSettings = LayoutSettings.getInstance(type); - - return layoutSettings.isFirstPageable(); - } - - public boolean isLayoutFriendliable(Layout layout) { - LayoutSettings layoutSettings = LayoutSettings.getInstance(layout); - - return layoutSettings.isURLFriendliable(); - } - - public boolean isLayoutFriendliable(String type) { - LayoutSettings layoutSettings = LayoutSettings.getInstance(type); - - return layoutSettings.isURLFriendliable(); - } - - public boolean isLayoutParentable(Layout layout) { - return isLayoutParentable(layout.getType()); - } - - public boolean isLayoutParentable(String type) { - LayoutSettings layoutSettings = LayoutSettings.getInstance(type); - - return layoutSettings.isParentable(); - } - - public boolean isLayoutSitemapable(Layout layout) { - if (layout.isPrivateLayout()) { - return false; - } - - LayoutSettings layoutSettings = LayoutSettings.getInstance(layout); - - return layoutSettings.isSitemapable(); - } - - public boolean isMethodGet(PortletRequest portletRequest) { - HttpServletRequest request = getHttpServletRequest(portletRequest); - - String method = GetterUtil.getString(request.getMethod()); - - if (method.equalsIgnoreCase(HttpMethods.GET)) { - return true; - } - else { - return false; - } - } - - public boolean isMethodPost(PortletRequest portletRequest) { - HttpServletRequest request = getHttpServletRequest(portletRequest); - - String method = GetterUtil.getString(request.getMethod()); - - if (method.equalsIgnoreCase(HttpMethods.POST)) { - return true; - } - else { - return false; - } - } - - public boolean isMultipartRequest(HttpServletRequest request) { - String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE); - - if ((contentType != null) && - contentType.startsWith(ContentTypes.MULTIPART_FORM_DATA)) { - - return true; - } - else { - return false; - } - } - - public boolean isOmniadmin(long userId) { - return OmniadminUtil.isOmniadmin(userId); - } - - public boolean isReservedParameter(String name) { - return _reservedParams.contains(name); - } - - public boolean isSecure(HttpServletRequest request) { - HttpSession session = request.getSession(); - - Boolean httpsInitial = (Boolean)session.getAttribute( - WebKeys.HTTPS_INITIAL); - - boolean secure = false; - - if ((PropsValues.COMPANY_SECURITY_AUTH_REQUIRES_HTTPS) && - (!PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) && - (httpsInitial != null) && (!httpsInitial.booleanValue())) { - - secure = false; - } - else { - secure = request.isSecure(); - } - - return secure; - } - - public boolean isSystemGroup(String groupName) { - if (groupName == null) { - return false; - } - - groupName = groupName.trim(); - - int pos = Arrays.binarySearch( - _sortedSystemGroups, groupName, new StringComparator()); - - if (pos >= 0) { - return true; - } - else { - return false; - } - } - - public boolean isSystemRole(String roleName) { - if (roleName == null) { - return false; - } - - roleName = roleName.trim(); - - int pos = Arrays.binarySearch( - _sortedSystemRoles, roleName, new StringComparator()); - - if (pos >= 0) { - return true; - } - else { - pos = Arrays.binarySearch( - _sortedSystemSiteRoles, roleName, new StringComparator()); - - if (pos >= 0) { - return true; - } - else { - pos = Arrays.binarySearch( - _sortedSystemOrganizationRoles, roleName, - new StringComparator()); - - if (pos >= 0) { - return true; - } - } - } - - return false; - } - - public boolean isUpdateAvailable() throws SystemException { - return PluginPackageUtil.isUpdateAvailable(); - } - - public boolean isValidResourceId(String resourceId) { - if (Validator.isNull(resourceId)) { - return true; - } - - Matcher matcher = _bannedResourceIdPattern.matcher(resourceId); - - if (matcher.matches()) { - return false; - } - - return true; - } - - public void removePortalPortEventListener( - PortalPortEventListener portalPortEventListener) { - - _portalPortEventListeners.remove(portalPortEventListener); - } - - public String renderPage( - ServletContext servletContext, HttpServletRequest request, - HttpServletResponse response, String path) - throws IOException, ServletException { - - RequestDispatcher requestDispatcher = - servletContext.getRequestDispatcher(path); - - StringServletResponse stringResponse = new StringServletResponse( - response); - - requestDispatcher.include(request, stringResponse); - - return stringResponse.getString(); - } - - public String renderPortlet( - ServletContext servletContext, HttpServletRequest request, - HttpServletResponse response, Portlet portlet, String queryString, - boolean writeOutput) - throws IOException, ServletException { - - return renderPortlet( - servletContext, request, response, portlet, queryString, null, null, - null, writeOutput); - } - - public String renderPortlet( - ServletContext servletContext, HttpServletRequest request, - HttpServletResponse response, Portlet portlet, String queryString, - String columnId, Integer columnPos, Integer columnCount, - boolean writeOutput) - throws IOException, ServletException { - - return renderPortlet( - servletContext, request, response, portlet, queryString, columnId, - columnPos, columnCount, null, writeOutput); - } - - public String renderPortlet( - ServletContext servletContext, HttpServletRequest request, - HttpServletResponse response, Portlet portlet, String queryString, - String columnId, Integer columnPos, Integer columnCount, - String path, boolean writeOutput) - throws IOException, ServletException { - - queryString = GetterUtil.getString(queryString); - columnId = GetterUtil.getString(columnId); - - if (columnPos == null) { - columnPos = Integer.valueOf(0); - } - - if (columnCount == null) { - columnCount = Integer.valueOf(0); - } - - request.setAttribute(WebKeys.RENDER_PORTLET, portlet); - request.setAttribute(WebKeys.RENDER_PORTLET_QUERY_STRING, queryString); - request.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_ID, columnId); - request.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_POS, columnPos); - request.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_COUNT, columnCount); - - if (path == null) { - path = "/html/portal/render_portlet.jsp"; - } - - RequestDispatcher requestDispatcher = - servletContext.getRequestDispatcher(path); - - UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter(); - - PipingServletResponse pipingServletResponse = new PipingServletResponse( - response, unsyncStringWriter); - - requestDispatcher.include(request, pipingServletResponse); - - boolean showPortlet = true; - - Boolean portletConfiguratorVisibility = (Boolean)request.getAttribute( - WebKeys.PORTLET_CONFIGURATOR_VISIBILITY); - - if (portletConfiguratorVisibility != null) { - ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( - WebKeys.THEME_DISPLAY); - - try { - Layout layout = themeDisplay.getLayout(); - - if (!layout.isTypeControlPanel() && - !LayoutPermissionUtil.contains( - themeDisplay.getPermissionChecker(), layout, - ActionKeys.UPDATE) && - !PortletPermissionUtil.contains( - themeDisplay.getPermissionChecker(), - themeDisplay.getPlid(), portlet.getPortletId(), - ActionKeys.CONFIGURATION)) { - - showPortlet = false; - } - } - catch (Exception e) { - throw new ServletException(e); - } - - request.removeAttribute(WebKeys.PORTLET_CONFIGURATOR_VISIBILITY); - } - - if (showPortlet) { - if (writeOutput) { - response.setContentType(ContentTypes.TEXT_HTML_UTF8); - - StringBundler sb = unsyncStringWriter.getStringBundler(); - - sb.writeTo(response.getWriter()); - - return StringPool.BLANK; - } - else { - return unsyncStringWriter.toString(); - } - } - else { - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); - - return StringPool.BLANK; - } - } - - public void resetCDNHosts() { - _cdnHostHttpMap.clear(); - _cdnHostHttpsMap.clear(); - - if (!ClusterInvokeThreadLocal.isEnabled()) { - return; - } - - ClusterRequest clusterRequest = ClusterRequest.createMulticastRequest( - _resetCDNHostsMethodHandler, true); - - try { - ClusterExecutorUtil.execute(clusterRequest); - } - catch (Exception e) { - _log.error("Unable to clear cluster wide CDN hosts", e); - } - } - - public Set resetPortletAddDefaultResourceCheckWhitelist() { - _portletAddDefaultResourceCheckWhitelist = SetUtil.fromArray( - PropsValues.PORTLET_ADD_DEFAULT_RESOURCE_CHECK_WHITELIST); - - _portletAddDefaultResourceCheckWhitelist = Collections.unmodifiableSet( - _portletAddDefaultResourceCheckWhitelist); - - return _portletAddDefaultResourceCheckWhitelist; - } - - public Set resetPortletAddDefaultResourceCheckWhitelistActions() { - _portletAddDefaultResourceCheckWhitelistActions = SetUtil.fromArray( - PropsValues.PORTLET_ADD_DEFAULT_RESOURCE_CHECK_WHITELIST_ACTIONS); - - _portletAddDefaultResourceCheckWhitelistActions = - Collections.unmodifiableSet( - _portletAddDefaultResourceCheckWhitelistActions); - - return _portletAddDefaultResourceCheckWhitelistActions; - } - - public void sendError( - Exception e, ActionRequest actionRequest, - ActionResponse actionResponse) - throws IOException { - - sendError(0, e, actionRequest, actionResponse); - } - - public void sendError( - Exception e, HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException { - - sendError(0, e, request, response); - } - - public void sendError( - int status, Exception e, ActionRequest actionRequest, - ActionResponse actionResponse) - throws IOException { - - StringBundler sb = new StringBundler(7); - - sb.append(_pathMain); - sb.append("/portal/status?status="); - sb.append(status); - sb.append("&exception="); - sb.append(e.getClass().getName()); - sb.append("&previousURL="); - sb.append(HttpUtil.encodeURL(getCurrentURL(actionRequest))); - - actionResponse.sendRedirect(sb.toString()); - } - - public void sendError( - int status, Exception e, HttpServletRequest request, - HttpServletResponse response) - throws IOException, ServletException { - - if (_log.isDebugEnabled()) { - String currentURL = (String)request.getAttribute( - WebKeys.CURRENT_URL); - - _log.debug( - "Current URL " + currentURL + " generates exception: " + - e.getMessage()); - } - - if (e instanceof NoSuchImageException) { - if (_logWebServerServlet.isWarnEnabled()) { - _logWebServerServlet.warn(e, e); - } - } - else if ((e instanceof PortalException) && _log.isDebugEnabled()) { - if ((e instanceof NoSuchLayoutException) || - (e instanceof PrincipalException)) { - - String msg = e.getMessage(); - - if (Validator.isNotNull(msg)) { - _log.debug(msg); - } - } - else { - _log.debug(e, e); - } - } - else if ((e instanceof SystemException) && _log.isWarnEnabled()) { - _log.warn(e, e); - } - - if (response.isCommitted()) { - return; - } - - if (status == 0) { - if (e instanceof PrincipalException) { - status = HttpServletResponse.SC_FORBIDDEN; - } - else { - String name = e.getClass().getName(); - - name = name.substring(name.lastIndexOf(CharPool.PERIOD) + 1); - - if (name.startsWith("NoSuch") && name.endsWith("Exception")) { - status = HttpServletResponse.SC_NOT_FOUND; - } - } - - if (status == 0) { - - // LPS-5352 - - if (PropsValues.TCK_URL) { - status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - } - else { - status = HttpServletResponse.SC_BAD_REQUEST; - } - } - } - - HttpSession session = request.getSession(); - - ServletContext servletContext = session.getServletContext(); - - String redirect = PATH_MAIN + "/portal/status"; - - if ((e instanceof NoSuchLayoutException) && - Validator.isNotNull( - PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND)) { - - response.setStatus(status); - - redirect = PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND; - - RequestDispatcher requestDispatcher = - servletContext.getRequestDispatcher(redirect); - - if (requestDispatcher != null) { - requestDispatcher.forward(request, response); - } - } - else if (PropsValues.LAYOUT_SHOW_HTTP_STATUS) { - response.setStatus(status); - - SessionErrors.add(request, e.getClass().getName(), e); - - RequestDispatcher requestDispatcher = - servletContext.getRequestDispatcher(redirect); - - if (requestDispatcher != null) { - requestDispatcher.forward(request, response); - } - } - else { - if (e != null) { - response.sendError(status, e.getMessage()); - } - else { - response.sendError(status); - } - } - } - - public void setPageDescription( - String description, HttpServletRequest request) { - - request.setAttribute(WebKeys.PAGE_DESCRIPTION, description); - } - - public void setPageKeywords(String keywords, HttpServletRequest request) { - request.removeAttribute(WebKeys.PAGE_KEYWORDS); - - addPageKeywords(keywords, request); - } - - public void setPageSubtitle(String subtitle, HttpServletRequest request) { - request.setAttribute(WebKeys.PAGE_SUBTITLE, subtitle); - } - - public void setPageTitle(String title, HttpServletRequest request) { - request.setAttribute(WebKeys.PAGE_TITLE, title); - } - - public void setPortalPort(HttpServletRequest request) { - if (request.isSecure()) { - if (_securePortalPort.get() == -1) { - int securePortalPort = request.getServerPort(); - - _securePortalPort.compareAndSet(-1, securePortalPort); - } - } - else { - if (_portalPort.get() == -1) { - int portalPort = request.getServerPort(); - - if (_portalPort.compareAndSet(-1, portalPort)) { - notifyPortalPortEventListeners(portalPort); - } - } - } - } - - public void storePreferences(PortletPreferences portletPreferences) - throws IOException, ValidatorException { - - PortletPreferencesWrapper portletPreferencesWrapper = - (PortletPreferencesWrapper)portletPreferences; - - PortletPreferencesImpl portletPreferencesImpl = - portletPreferencesWrapper.getPortletPreferencesImpl(); - - portletPreferencesImpl.store(); - } - - public String[] stripURLAnchor(String url, String separator) { - String anchor = StringPool.BLANK; - - int pos = url.indexOf(separator); - - if (pos != -1) { - anchor = url.substring(pos); - url = url.substring(0, pos); - } - - return new String[] {url, anchor}; - } - - public String transformCustomSQL(String sql) { - if ((_customSqlKeys == null) || (_customSqlValues == null)) { - initCustomSQL(); - } - - return StringUtil.replace(sql, _customSqlKeys, _customSqlValues); - } - - public PortletMode updatePortletMode( - String portletId, User user, Layout layout, PortletMode portletMode, - HttpServletRequest request) { - - LayoutTypePortlet layoutType = - (LayoutTypePortlet)layout.getLayoutType(); - - if ((portletMode == null) || Validator.isNull(portletMode.toString())) { - if (layoutType.hasModeAboutPortletId(portletId)) { - return LiferayPortletMode.ABOUT; - } - else if (layoutType.hasModeConfigPortletId(portletId)) { - return LiferayPortletMode.CONFIG; - } - else if (layoutType.hasModeEditPortletId(portletId)) { - return PortletMode.EDIT; - } - else if (layoutType.hasModeEditDefaultsPortletId(portletId)) { - return LiferayPortletMode.EDIT_DEFAULTS; - } - else if (layoutType.hasModeEditGuestPortletId(portletId)) { - return LiferayPortletMode.EDIT_GUEST; - } - else if (layoutType.hasModeHelpPortletId(portletId)) { - return PortletMode.HELP; - } - else if (layoutType.hasModePreviewPortletId(portletId)) { - return LiferayPortletMode.PREVIEW; - } - else if (layoutType.hasModePrintPortletId(portletId)) { - return LiferayPortletMode.PRINT; - } - else { - return PortletMode.VIEW; - } - } - else { - boolean updateLayout = false; - - if (portletMode.equals(LiferayPortletMode.ABOUT) && - !layoutType.hasModeAboutPortletId(portletId)) { - - layoutType.addModeAboutPortletId(portletId); - - updateLayout = true; - } - else if (portletMode.equals(LiferayPortletMode.CONFIG) && - !layoutType.hasModeConfigPortletId(portletId)) { - - layoutType.addModeConfigPortletId(portletId); - - updateLayout = true; - } - else if (portletMode.equals(PortletMode.EDIT) && - !layoutType.hasModeEditPortletId(portletId)) { - - layoutType.addModeEditPortletId(portletId); - - updateLayout = true; - } - else if (portletMode.equals(LiferayPortletMode.EDIT_DEFAULTS) && - !layoutType.hasModeEditDefaultsPortletId(portletId)) { - - layoutType.addModeEditDefaultsPortletId(portletId); - - updateLayout = true; - } - else if (portletMode.equals(LiferayPortletMode.EDIT_GUEST) && - !layoutType.hasModeEditGuestPortletId(portletId)) { - - layoutType.addModeEditGuestPortletId(portletId); - - updateLayout = true; - } - else if (portletMode.equals(PortletMode.HELP) && - !layoutType.hasModeHelpPortletId(portletId)) { - - layoutType.addModeHelpPortletId(portletId); - - updateLayout = true; - } - else if (portletMode.equals(LiferayPortletMode.PREVIEW) && - !layoutType.hasModePreviewPortletId(portletId)) { - - layoutType.addModePreviewPortletId(portletId); - - updateLayout = true; - } - else if (portletMode.equals(LiferayPortletMode.PRINT) && - !layoutType.hasModePrintPortletId(portletId)) { - - layoutType.addModePrintPortletId(portletId); - - updateLayout = true; - } - else if (portletMode.equals(PortletMode.VIEW) && - !layoutType.hasModeViewPortletId(portletId)) { - - layoutType.removeModesPortletId(portletId); - - updateLayout = true; - } - - if (updateLayout) { - LayoutClone layoutClone = LayoutCloneFactory.getInstance(); - - if (layoutClone != null) { - layoutClone.update( - request, layout.getPlid(), layout.getTypeSettings()); - } - } - - return portletMode; - } - } - - public String updateRedirect( - String redirect, String oldPath, String newPath) { - - if (Validator.isNotNull(redirect) && (oldPath != null) && - !oldPath.equals(newPath)) { - - redirect = StringUtil.replace(redirect, oldPath, newPath); - redirect = StringUtil.replace( - redirect, HttpUtil.encodeURL(oldPath), - HttpUtil.encodeURL(newPath)); - } - - return redirect; - } - - public WindowState updateWindowState( - String portletId, User user, Layout layout, WindowState windowState, - HttpServletRequest request) { - - LayoutTypePortlet layoutType = - (LayoutTypePortlet)layout.getLayoutType(); - - if ((windowState == null) || - (Validator.isNull(windowState.toString()))) { - - if (layoutType.hasStateMaxPortletId(portletId)) { - windowState = WindowState.MAXIMIZED; - } - else if (layoutType.hasStateMinPortletId(portletId)) { - windowState = WindowState.MINIMIZED; - } - else { - windowState = WindowState.NORMAL; - } - } - else { - boolean updateLayout = false; - - if (windowState.equals(WindowState.MAXIMIZED) && - !layoutType.hasStateMaxPortletId(portletId)) { - - layoutType.addStateMaxPortletId(portletId); - - if (PropsValues.LAYOUT_REMEMBER_MAXIMIZED_WINDOW_STATE) { - updateLayout = true; - } - } - else if (windowState.equals(WindowState.MINIMIZED) && - !layoutType.hasStateMinPortletId(portletId)) { - - layoutType.addStateMinPortletId(portletId); - - updateLayout = true; - } - else if (windowState.equals(WindowState.NORMAL) && - !layoutType.hasStateNormalPortletId(portletId)) { - - layoutType.removeStatesPortletId(portletId); - - updateLayout = true; - } - - if (portletId.equals(PortletKeys.LAYOUTS_ADMIN) || - portletId.equals(PortletKeys.PORTLET_CONFIGURATION)) { - - updateLayout = false; - } - - if (updateLayout) { - LayoutClone layoutClone = LayoutCloneFactory.getInstance(); - - if (layoutClone != null) { - layoutClone.update( - request, layout.getPlid(), layout.getTypeSettings()); - } - } - } - - ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( - WebKeys.THEME_DISPLAY); - - themeDisplay.setStateExclusive( - windowState.equals(LiferayWindowState.EXCLUSIVE)); - themeDisplay.setStateMaximized( - windowState.equals(WindowState.MAXIMIZED)); - themeDisplay.setStatePopUp( - windowState.equals(LiferayWindowState.POP_UP)); - - if (themeDisplay.isStateMaximized() && - themeDisplay.isShowAddContentIcon()) { - - themeDisplay.setShowAddContentIcon(false); - } - else if (!themeDisplay.isStateMaximized() && - !themeDisplay.isShowAddContentIcon() && - themeDisplay.isShowAddContentIconPermission()) { - - themeDisplay.setShowAddContentIcon(true); - } - - request.setAttribute(WebKeys.WINDOW_STATE, windowState); - - return windowState; - } - - protected void addDefaultResource( - long companyId, Layout layout, Portlet portlet, - boolean portletActions) - throws PortalException, SystemException { - - String rootPortletId = portlet.getRootPortletId(); - - String portletPrimaryKey = PortletPermissionUtil.getPrimaryKey( - layout.getPlid(), portlet.getPortletId()); - - String name = null; - String primaryKey = null; - - if (portletActions) { - name = rootPortletId; - primaryKey = portletPrimaryKey; - } - else { - name = ResourceActionsUtil.getPortletBaseResource(rootPortletId); - primaryKey = String.valueOf( - getScopeGroupId(layout, portlet.getPortletId())); - } - - if (Validator.isNull(name)) { - return; - } - - try { - if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { - int count = - ResourcePermissionLocalServiceUtil. - getResourcePermissionsCount( - companyId, name, - ResourceConstants.SCOPE_INDIVIDUAL, primaryKey); - - if (count == 0) { - throw new NoSuchResourceException(); - } - } - else if (!portlet.isUndeployedPortlet()) { - ResourceLocalServiceUtil.getResource( - companyId, name, - ResourceConstants.SCOPE_INDIVIDUAL, primaryKey); - } - } - catch (NoSuchResourceException nsre) { - ResourceLocalServiceUtil.addResources( - companyId, layout.getGroupId(), 0, name, primaryKey, - portletActions, true, true); - } - } - - protected void addDefaultResource( - ThemeDisplay themeDisplay, Layout layout, Portlet portlet, - boolean portletActions) - throws PortalException, SystemException { - - addDefaultResource( - themeDisplay.getCompanyId(), layout, portlet, portletActions); - } - - protected String buildI18NPath(Locale locale) { - String languageId = LocaleUtil.toLanguageId(locale); - - if (Validator.isNull(languageId)) { - return null; - } - - if (LanguageUtil.isDuplicateLanguageCode(locale.getLanguage())) { - Locale priorityLocale = LanguageUtil.getLocale( - locale.getLanguage()); - - if (locale.equals(priorityLocale)) { - languageId = locale.getLanguage(); - } - } - else { - languageId = locale.getLanguage(); - } - - return StringPool.SLASH.concat(languageId); - } - - protected long doGetPlidFromPortletId( - long groupId, boolean privateLayout, String portletId) - throws PortalException, SystemException { - - long scopeGroupId = groupId; - - try { - Group group = GroupLocalServiceUtil.getGroup(groupId); - - if (group.isLayout()) { - Layout scopeLayout = LayoutLocalServiceUtil.getLayout( - group.getClassPK()); - - groupId = scopeLayout.getGroupId(); - } - } - catch (Exception e) { - } - - long plid = LayoutConstants.DEFAULT_PLID; - - List layouts = LayoutLocalServiceUtil.getLayouts( - groupId, privateLayout, LayoutConstants.TYPE_PORTLET); - - for (Layout layout : layouts) { - LayoutTypePortlet layoutTypePortlet = - (LayoutTypePortlet)layout.getLayoutType(); - - if (layoutTypePortlet.hasPortletId(portletId)) { - if (getScopeGroupId(layout, portletId) == scopeGroupId) { - plid = layout.getPlid(); - - break; - } - } - } - - return plid; - } - - protected List filterControlPanelPortlets( - Set portlets, String category, ThemeDisplay themeDisplay) { - - Group group = themeDisplay.getScopeGroup(); - - List filteredPortlets = new ArrayList(); - - if (category.equals(PortletCategoryKeys.CONTENT) && group.isLayout()) { - for (Portlet portlet : portlets) { - if (portlet.isScopeable()) { - filteredPortlets.add(portlet); - } - } - } - else { - filteredPortlets.addAll(portlets); - } - - Iterator itr = filteredPortlets.iterator(); - - while (itr.hasNext()) { - Portlet portlet = itr.next(); - - try { - ControlPanelEntry controlPanelEntry = - portlet.getControlPanelEntryInstance(); - - if (controlPanelEntry == null) { - controlPanelEntry = - DefaultControlPanelEntryFactory.getInstance(); - } - - if (!controlPanelEntry.isVisible( - portlet, category, themeDisplay)) { - - itr.remove(); - } - } - catch (Exception e) { - _log.error(e, e); - - itr.remove(); - } - } - - return filteredPortlets; - } - - protected long getDefaultScopeGroupId(long companyId) - throws PortalException, SystemException { - - long doAsGroupId = 0; - - Collection portlets = getControlPanelPortlets( - companyId, PortletCategoryKeys.CONTENT); - - List groups = GroupServiceUtil.getManageableSites(portlets, 1); - - if (!groups.isEmpty()) { - Group group = groups.get(0); - - doAsGroupId = group.getGroupId(); - } - else { - Group guestGroup = GroupLocalServiceUtil.fetchGroup( - companyId, GroupConstants.GUEST); - - if (guestGroup != null) { - doAsGroupId = guestGroup.getGroupId(); - } - } - - return doAsGroupId; - } - - protected long getDoAsUserId( - HttpServletRequest request, String doAsUserIdString, - boolean alwaysAllowDoAsUser) - throws Exception { - - if (Validator.isNull(doAsUserIdString)) { - return 0; - } - - long doAsUserId = 0; - - try { - Company company = getCompany(request); - - doAsUserId = GetterUtil.getLong( - Encryptor.decrypt(company.getKeyObj(), doAsUserIdString)); - } - catch (Exception e) { - if (_log.isWarnEnabled()) { - _log.warn( - "Unable to impersonate " + doAsUserIdString + - " because the string cannot be decrypted", - e); - } - - return 0; - } - - if (_log.isDebugEnabled()) { - if (alwaysAllowDoAsUser) { - _log.debug( - "doAsUserId path or Struts action is always allowed"); - } - else { - _log.debug( - "doAsUserId path is Struts action not always allowed"); - } - } - - if (alwaysAllowDoAsUser) { - request.setAttribute(WebKeys.USER_ID, new Long(doAsUserId)); - - return doAsUserId; - } - - HttpSession session = request.getSession(); - - Long realUserIdObj = (Long)session.getAttribute(WebKeys.USER_ID); - - if (realUserIdObj == null) { - return 0; - } - - User doAsUser = UserLocalServiceUtil.getUserById(doAsUserId); - - long[] organizationIds = doAsUser.getOrganizationIds(); - - User realUser = UserLocalServiceUtil.getUserById( - realUserIdObj.longValue()); - boolean checkGuest = true; - - PermissionChecker permissionChecker = - PermissionCheckerFactoryUtil.create(realUser, checkGuest); - - if (doAsUser.isDefaultUser() || - UserPermissionUtil.contains( - permissionChecker, doAsUserId, organizationIds, - ActionKeys.IMPERSONATE)) { - - request.setAttribute(WebKeys.USER_ID, new Long(doAsUserId)); - - return doAsUserId; - } - else { - _log.error( - "User " + realUserIdObj + " does not have the permission " + - "to impersonate " + doAsUserId); - - return 0; - } - } - - protected String getGroupFriendlyURL( - Group group, boolean privateLayoutSet, ThemeDisplay themeDisplay, - boolean canonicalURL) - throws PortalException, SystemException { - - LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet( - group.getGroupId(), privateLayoutSet); - - String portalURL = StringPool.BLANK; - - if (canonicalURL || !themeDisplay.getServerName().equals(_LOCALHOST)) { - String virtualHostname = layoutSet.getVirtualHostname(); - - if (Validator.isNull(virtualHostname) && - Validator.isNotNull( - PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME) && - !layoutSet.isPrivateLayout()) { - - try { - Group defaultGroup = GroupLocalServiceUtil.getGroup( - themeDisplay.getCompanyId(), - PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME); - - if (layoutSet.getGroupId() == defaultGroup.getGroupId()) { - Company company = themeDisplay.getCompany(); - - virtualHostname = company.getVirtualHostname(); - } - } - catch (Exception e) { - _log.error(e, e); - } - } - - if (Validator.isNotNull(virtualHostname) && - (canonicalURL || - !virtualHostname.equalsIgnoreCase(_LOCALHOST))) { - - virtualHostname = getPortalURL( - virtualHostname, themeDisplay.getServerPort(), - themeDisplay.isSecure()); - - String portalDomain = HttpUtil.getDomain( - themeDisplay.getPortalURL()); - - if (canonicalURL || virtualHostname.contains(portalDomain)) { - String path = StringPool.BLANK; - - if (themeDisplay.isWidget()) { - path = PropsValues.WIDGET_SERVLET_MAPPING; - } - - if (themeDisplay.isI18n() && !canonicalURL) { - path = themeDisplay.getI18nPath(); - } - - return virtualHostname.concat(_pathContext).concat(path); - } - } - else { - Layout curLayout = themeDisplay.getLayout(); - - LayoutSet curLayoutSet = curLayout.getLayoutSet(); - - if (canonicalURL || - ((layoutSet.getLayoutSetId() != - curLayoutSet.getLayoutSetId()) && - (group.getClassPK() != themeDisplay.getUserId()))) { - - if (group.isControlPanel()) { - virtualHostname = curLayoutSet.getVirtualHostname(); - } - - if (Validator.isNull(virtualHostname) || - virtualHostname.equalsIgnoreCase(_LOCALHOST)) { - - Company company = themeDisplay.getCompany(); - - virtualHostname = company.getVirtualHostname(); - } - - if (canonicalURL || - !virtualHostname.equalsIgnoreCase(_LOCALHOST)) { - - portalURL = getPortalURL( - virtualHostname, themeDisplay.getServerPort(), - themeDisplay.isSecure()); - } - } - } - } - - String friendlyURL = null; - - if (privateLayoutSet) { - if (group.isUser()) { - friendlyURL = _PRIVATE_USER_SERVLET_MAPPING; - } - else { - friendlyURL = _PRIVATE_GROUP_SERVLET_MAPPING; - } - } - else { - friendlyURL = _PUBLIC_GROUP_SERVLET_MAPPING; - } - - StringBundler sb = new StringBundler(6); - - sb.append(portalURL); - sb.append(_pathContext); - - if (themeDisplay.isI18n() && !canonicalURL) { - sb.append(themeDisplay.getI18nPath()); - } - - if (themeDisplay.isWidget()) { - sb.append(PropsValues.WIDGET_SERVLET_MAPPING); - } - - sb.append(friendlyURL); - sb.append(group.getFriendlyURL()); - - return sb.toString(); - } - - protected String getPortletParam(HttpServletRequest request, String name) { - String portletId = ParamUtil.getString(request, "p_p_id"); - - if (Validator.isNull(portletId)) { - return StringPool.BLANK; - } - - String value = null; - - int valueCount = 0; - - String keyName = StringPool.UNDERLINE.concat(name); - - Map parameterMap = request.getParameterMap(); - - for (Map.Entry entry : parameterMap.entrySet()) { - String parameterName = entry.getKey(); - - int pos = parameterName.indexOf(keyName); - - if (pos == -1) { - continue; - } - - valueCount++; - - // There should never be more than one value - - if (valueCount > 1) { - return StringPool.BLANK; - } - - String[] parameterValues = entry.getValue(); - - if ((parameterValues == null) || (parameterValues.length == 0) || - Validator.isNull(parameterValues[0])) { - - continue; - } - - // The Struts action must be for the correct portlet - - String portletId1 = parameterName.substring(1, pos); - - if (portletId.equals(portletId1)) { - value = parameterValues[0]; - } - } - - if (value == null) { - value = StringPool.BLANK; - } - - return value; - } - - protected String getServletURL( - Portlet portlet, String servletPath, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - Layout layout = themeDisplay.getLayout(); - - StringBundler sb = new StringBundler(); - - sb.append(themeDisplay.getPortalURL()); - - if (Validator.isNotNull(_pathContext)) { - sb.append(_pathContext); - } - - if (themeDisplay.isI18n()) { - sb.append(themeDisplay.getI18nPath()); - } - - sb.append(servletPath); - - Group group = layout.getGroup(); - - if (layout.isPrivateLayout()) { - if (group.isUser()) { - sb.append(_PRIVATE_USER_SERVLET_MAPPING); - } - else { - sb.append(_PRIVATE_GROUP_SERVLET_MAPPING); - } - } - else { - sb.append(_PUBLIC_GROUP_SERVLET_MAPPING); - } - - sb.append(group.getFriendlyURL()); - sb.append(layout.getFriendlyURL()); - - sb.append(FRIENDLY_URL_SEPARATOR); - - FriendlyURLMapper friendlyURLMapper = - portlet.getFriendlyURLMapperInstance(); - - if ((friendlyURLMapper != null) && !portlet.isInstanceable()) { - sb.append(friendlyURLMapper.getMapping()); - } - else { - sb.append(portlet.getPortletId()); - } - - return sb.toString(); - } - - protected boolean isAlwaysAllowDoAsUser(HttpServletRequest request) - throws Exception { - - String ticketKey = ParamUtil.getString(request, "ticketKey"); - - if (Validator.isNull(ticketKey)) { - return false; - } - - Ticket ticket = TicketLocalServiceUtil.fetchTicket(ticketKey); - - if (ticket == null) { - return false; - } - - String className = ticket.getClassName(); - - if (!className.equals(User.class.getName())) { - return false; - } - - long doAsUserId = 0; - - try { - Company company = getCompany(request); - - String doAsUserIdString = ParamUtil.getString( - request, "doAsUserId"); - - if (Validator.isNotNull(doAsUserIdString)) { - doAsUserId = GetterUtil.getLong( - Encryptor.decrypt(company.getKeyObj(), doAsUserIdString)); - } - } - catch (Exception e) { - return false; - } - - if ((ticket.getClassPK() != doAsUserId) || - (ticket.getType() != TicketConstants.TYPE_IMPERSONATE)) { - - return false; - } - - if (ticket.isExpired()) { - TicketLocalServiceUtil.deleteTicket(ticket); - - return false; - } - - Date expirationDate = new Date( - System.currentTimeMillis() + - PropsValues.SESSION_TIMEOUT * Time.MINUTE); - - ticket.setExpirationDate(expirationDate); - - TicketLocalServiceUtil.updateTicket(ticket, false); - - return true; - } - - protected boolean isPanelSelectedPortlet( - ThemeDisplay themeDisplay, String portletId) { - - Layout layout = themeDisplay.getLayout(); - - String panelSelectedPortlets = layout.getTypeSettingsProperty( - "panelSelectedPortlets"); - - if (Validator.isNotNull(panelSelectedPortlets)) { - String[] panelSelectedPortletsArray = StringUtil.split( - panelSelectedPortlets); - - return ArrayUtil.contains(panelSelectedPortletsArray, portletId); - } - - return false; - } - - protected void notifyPortalPortEventListeners(int portalPort) { - for (PortalPortEventListener portalPortEventListener : - _portalPortEventListeners) { - - portalPortEventListener.portalPortConfigured(portalPort); - } - } - - protected String removeRedirectParameter(String url) { - String queryString = HttpUtil.getQueryString(url); - - Map parameterMap = HttpUtil.getParameterMap( - queryString); - - for (String parameter : parameterMap.keySet()) { - if (parameter.endsWith("redirect")) { - url = HttpUtil.removeParameter(url, parameter); - } - } - - return url; - } - - private static final String _J_SECURITY_CHECK = "j_security_check"; - - private static final String _JSESSIONID = ";jsessionid="; - - private static final String _LOCALHOST = "localhost"; - - private static final String _PRIVATE_GROUP_SERVLET_MAPPING = - PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING; - - private static final String _PRIVATE_USER_SERVLET_MAPPING = - PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING; - - private static final String _PUBLIC_GROUP_SERVLET_MAPPING = - PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING; - - private static Log _log = LogFactoryUtil.getLog(PortalImpl.class); - - private static Log _logWebServerServlet = LogFactoryUtil.getLog( - WebServerServlet.class); - - private static Map _cdnHostHttpMap = - new ConcurrentHashMap(); - private static Map _cdnHostHttpsMap = - new ConcurrentHashMap(); - private static MethodHandler _resetCDNHostsMethodHandler = - new MethodHandler( - new MethodKey(PortalUtil.class.getName(), "resetCDNHosts")); - private static Date _upTime = new Date(); - - private String[] _allSystemGroups; - private String[] _allSystemOrganizationRoles; - private String[] _allSystemRoles; - private String[] _allSystemSiteRoles; - private Set _authTokenIgnoreActions; - private Set _authTokenIgnorePortlets; - private Pattern _bannedResourceIdPattern = Pattern.compile( - PropsValues.PORTLET_RESOURCE_ID_BANNED_PATHS_REGEXP, - Pattern.CASE_INSENSITIVE); - private String _computerAddress; - private String _computerName; - private String[] _customSqlKeys; - private String[] _customSqlValues; - private String _pathContext; - private String _pathFriendlyURLPrivateGroup; - private String _pathFriendlyURLPrivateUser; - private String _pathFriendlyURLPublic; - private String _pathImage; - private String _pathMain; - private String _pathProxy; - private Map _plidToPortletIdMap = - new ConcurrentHashMap(); - private final AtomicInteger _portalPort = new AtomicInteger(-1); - private List _portalPortEventListeners = - new ArrayList(); - private Set _portletAddDefaultResourceCheckWhitelist; - private Set _portletAddDefaultResourceCheckWhitelistActions; - private Set _reservedParams; - private final AtomicInteger _securePortalPort = new AtomicInteger(-1); - private String[] _sortedSystemGroups; - private String[] _sortedSystemOrganizationRoles; - private String[] _sortedSystemRoles; - private String[] _sortedSystemSiteRoles; - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portal.util; + +import com.liferay.portal.NoSuchCompanyException; +import com.liferay.portal.NoSuchImageException; +import com.liferay.portal.NoSuchLayoutException; +import com.liferay.portal.NoSuchResourceException; +import com.liferay.portal.NoSuchUserException; +import com.liferay.portal.cluster.ClusterInvokeThreadLocal; +import com.liferay.portal.kernel.bean.BeanPropertiesUtil; +import com.liferay.portal.kernel.cluster.ClusterExecutorUtil; +import com.liferay.portal.kernel.cluster.ClusterRequest; +import com.liferay.portal.kernel.dao.db.DB; +import com.liferay.portal.kernel.dao.db.DBFactoryUtil; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.io.unsync.UnsyncStringWriter; +import com.liferay.portal.kernel.language.LanguageUtil; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.portlet.FriendlyURLMapper; +import com.liferay.portal.kernel.portlet.FriendlyURLMapperThreadLocal; +import com.liferay.portal.kernel.portlet.LiferayPortletMode; +import com.liferay.portal.kernel.portlet.LiferayPortletRequest; +import com.liferay.portal.kernel.portlet.LiferayPortletResponse; +import com.liferay.portal.kernel.portlet.LiferayWindowState; +import com.liferay.portal.kernel.portlet.PortletBag; +import com.liferay.portal.kernel.portlet.PortletBagPool; +import com.liferay.portal.kernel.servlet.BrowserSnifferUtil; +import com.liferay.portal.kernel.servlet.FileTimestampUtil; +import com.liferay.portal.kernel.servlet.HttpHeaders; +import com.liferay.portal.kernel.servlet.HttpMethods; +import com.liferay.portal.kernel.servlet.PipingServletResponse; +import com.liferay.portal.kernel.servlet.SessionErrors; +import com.liferay.portal.kernel.servlet.StringServletResponse; +import com.liferay.portal.kernel.servlet.taglib.ui.BreadcrumbEntry; +import com.liferay.portal.kernel.upload.UploadPortletRequest; +import com.liferay.portal.kernel.upload.UploadServletRequest; +import com.liferay.portal.kernel.util.ArrayUtil; +import com.liferay.portal.kernel.util.Base64; +import com.liferay.portal.kernel.util.CalendarFactoryUtil; +import com.liferay.portal.kernel.util.CharPool; +import com.liferay.portal.kernel.util.ContentTypes; +import com.liferay.portal.kernel.util.ContextPathUtil; +import com.liferay.portal.kernel.util.DeterminateKeyGenerator; +import com.liferay.portal.kernel.util.GetterUtil; +import com.liferay.portal.kernel.util.HtmlUtil; +import com.liferay.portal.kernel.util.Http; +import com.liferay.portal.kernel.util.HttpUtil; +import com.liferay.portal.kernel.util.InheritableMap; +import com.liferay.portal.kernel.util.JavaConstants; +import com.liferay.portal.kernel.util.ListUtil; +import com.liferay.portal.kernel.util.LocaleUtil; +import com.liferay.portal.kernel.util.MethodHandler; +import com.liferay.portal.kernel.util.MethodKey; +import com.liferay.portal.kernel.util.ParamUtil; +import com.liferay.portal.kernel.util.PropsKeys; +import com.liferay.portal.kernel.util.ReleaseInfo; +import com.liferay.portal.kernel.util.SetUtil; +import com.liferay.portal.kernel.util.StringBundler; +import com.liferay.portal.kernel.util.StringComparator; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.Time; +import com.liferay.portal.kernel.util.UnicodeProperties; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.kernel.xml.QName; +import com.liferay.portal.model.BaseModel; +import com.liferay.portal.model.ClassName; +import com.liferay.portal.model.ColorScheme; +import com.liferay.portal.model.Company; +import com.liferay.portal.model.Group; +import com.liferay.portal.model.GroupConstants; +import com.liferay.portal.model.Layout; +import com.liferay.portal.model.LayoutConstants; +import com.liferay.portal.model.LayoutSet; +import com.liferay.portal.model.LayoutType; +import com.liferay.portal.model.LayoutTypePortlet; +import com.liferay.portal.model.LayoutTypePortletConstants; +import com.liferay.portal.model.Organization; +import com.liferay.portal.model.Portlet; +import com.liferay.portal.model.PublicRenderParameter; +import com.liferay.portal.model.Resource; +import com.liferay.portal.model.ResourceCode; +import com.liferay.portal.model.ResourceConstants; +import com.liferay.portal.model.ResourcePermission; +import com.liferay.portal.model.Role; +import com.liferay.portal.model.RoleConstants; +import com.liferay.portal.model.Theme; +import com.liferay.portal.model.Ticket; +import com.liferay.portal.model.TicketConstants; +import com.liferay.portal.model.User; +import com.liferay.portal.model.UserGroup; +import com.liferay.portal.model.VirtualLayoutConstants; +import com.liferay.portal.model.impl.LayoutTypePortletImpl; +import com.liferay.portal.model.impl.VirtualLayout; +import com.liferay.portal.plugin.PluginPackageUtil; +import com.liferay.portal.security.auth.AuthException; +import com.liferay.portal.security.auth.AuthTokenUtil; +import com.liferay.portal.security.auth.CompanyThreadLocal; +import com.liferay.portal.security.auth.PrincipalException; +import com.liferay.portal.security.permission.ActionKeys; +import com.liferay.portal.security.permission.PermissionChecker; +import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; +import com.liferay.portal.security.permission.ResourceActionsUtil; +import com.liferay.portal.service.ClassNameLocalServiceUtil; +import com.liferay.portal.service.CompanyLocalServiceUtil; +import com.liferay.portal.service.GroupLocalServiceUtil; +import com.liferay.portal.service.GroupServiceUtil; +import com.liferay.portal.service.LayoutLocalServiceUtil; +import com.liferay.portal.service.LayoutSetLocalServiceUtil; +import com.liferay.portal.service.PortletLocalServiceUtil; +import com.liferay.portal.service.ResourceCodeLocalServiceUtil; +import com.liferay.portal.service.ResourceLocalServiceUtil; +import com.liferay.portal.service.ResourcePermissionLocalServiceUtil; +import com.liferay.portal.service.TicketLocalServiceUtil; +import com.liferay.portal.service.UserLocalServiceUtil; +import com.liferay.portal.service.UserServiceUtil; +import com.liferay.portal.service.permission.GroupPermissionUtil; +import com.liferay.portal.service.permission.LayoutPermissionUtil; +import com.liferay.portal.service.permission.LayoutPrototypePermissionUtil; +import com.liferay.portal.service.permission.LayoutSetPrototypePermissionUtil; +import com.liferay.portal.service.permission.OrganizationPermissionUtil; +import com.liferay.portal.service.permission.PortletPermissionUtil; +import com.liferay.portal.service.permission.UserPermissionUtil; +import com.liferay.portal.servlet.filters.i18n.I18nFilter; +import com.liferay.portal.servlet.filters.secure.NonceUtil; +import com.liferay.portal.struts.StrutsUtil; +import com.liferay.portal.theme.ThemeDisplay; +import com.liferay.portal.upload.UploadPortletRequestImpl; +import com.liferay.portal.upload.UploadServletRequestImpl; +import com.liferay.portal.util.comparator.PortletControlPanelWeightComparator; +import com.liferay.portal.webserver.WebServerServlet; +import com.liferay.portlet.ActionResponseImpl; +import com.liferay.portlet.ControlPanelEntry; +import com.liferay.portlet.DefaultControlPanelEntryFactory; +import com.liferay.portlet.PortletConfigFactoryUtil; +import com.liferay.portlet.PortletConfigImpl; +import com.liferay.portlet.PortletContextImpl; +import com.liferay.portlet.PortletPreferencesFactoryUtil; +import com.liferay.portlet.PortletPreferencesImpl; +import com.liferay.portlet.PortletPreferencesThreadLocal; +import com.liferay.portlet.PortletPreferencesWrapper; +import com.liferay.portlet.PortletQNameUtil; +import com.liferay.portlet.PortletRequestImpl; +import com.liferay.portlet.PortletResponseImpl; +import com.liferay.portlet.PortletURLFactoryUtil; +import com.liferay.portlet.PortletURLImpl; +import com.liferay.portlet.RenderRequestImpl; +import com.liferay.portlet.RenderResponseImpl; +import com.liferay.portlet.StateAwareResponseImpl; +import com.liferay.portlet.UserAttributes; +import com.liferay.portlet.admin.util.OmniadminUtil; +import com.liferay.portlet.asset.model.AssetTag; +import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil; +import com.liferay.portlet.blogs.model.BlogsEntry; +import com.liferay.portlet.bookmarks.model.BookmarksEntry; +import com.liferay.portlet.calendar.model.CalEvent; +import com.liferay.portlet.documentlibrary.model.DLFileEntry; +import com.liferay.portlet.expando.ValueDataException; +import com.liferay.portlet.expando.model.ExpandoBridge; +import com.liferay.portlet.expando.model.ExpandoColumnConstants; +import com.liferay.portlet.journal.asset.JournalArticleAssetRendererFactory; +import com.liferay.portlet.journal.model.JournalArticle; +import com.liferay.portlet.journal.model.JournalArticleConstants; +import com.liferay.portlet.journal.service.JournalArticleLocalServiceUtil; +import com.liferay.portlet.login.util.LoginUtil; +import com.liferay.portlet.messageboards.model.MBMessage; +import com.liferay.portlet.messageboards.model.MBThread; +import com.liferay.portlet.social.model.SocialRelationConstants; +import com.liferay.portlet.social.util.FacebookUtil; +import com.liferay.portlet.wiki.model.WikiPage; +import com.liferay.util.Encryptor; +import com.liferay.util.JS; +import com.liferay.util.PwdGenerator; +import com.liferay.util.UniqueList; +import com.liferay.util.servlet.DynamicServletRequest; + +import java.io.IOException; +import java.io.Serializable; + +import java.lang.reflect.Method; + +import java.net.InetAddress; +import java.net.UnknownHostException; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.ResourceBundle; +import java.util.Set; +import java.util.TimeZone; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.portlet.ActionRequest; +import javax.portlet.ActionResponse; +import javax.portlet.PortletConfig; +import javax.portlet.PortletMode; +import javax.portlet.PortletPreferences; +import javax.portlet.PortletRequest; +import javax.portlet.PortletResponse; +import javax.portlet.PortletURL; +import javax.portlet.PreferencesValidator; +import javax.portlet.RenderRequest; +import javax.portlet.RenderResponse; +import javax.portlet.ValidatorException; +import javax.portlet.WindowState; + +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.servlet.jsp.PageContext; + +import org.apache.struts.Globals; + +/** + * @author Brian Wing Shun Chan + * @author Brian Myunghun Kim + * @author Jorge Ferrer + * @author Raymond Augé + * @author Eduardo Lundgren + * @author Wesley Gong + * @author Hugo Huijser + * @author Juan Fernández + */ +public class PortalImpl implements Portal { + + public PortalImpl() { + + // Computer name + + _computerName = System.getProperty("env.COMPUTERNAME"); + + if (Validator.isNull(_computerName)) { + _computerName = System.getProperty("env.HOST"); + } + + if (Validator.isNull(_computerName)) { + _computerName = System.getProperty("env.HOSTNAME"); + } + + if (Validator.isNull(_computerName)) { + try { + _computerName = InetAddress.getLocalHost().getHostName(); + } + catch (UnknownHostException uhe) { + } + } + + try { + _computerAddress = InetAddress.getByName( + _computerName).getHostAddress(); + } + catch (UnknownHostException uhe) { + } + + if (Validator.isNull(_computerAddress)) { + try { + _computerAddress = InetAddress.getLocalHost().getHostAddress(); + } + catch (UnknownHostException uhe) { + } + } + + // Paths + + _pathProxy = PropsValues.PORTAL_PROXY_PATH; + + _pathContext = ContextPathUtil.getContextPath(PropsValues.PORTAL_CTX); + _pathContext = _pathProxy.concat(_pathContext); + + _pathFriendlyURLPrivateGroup = + _pathContext + _PRIVATE_GROUP_SERVLET_MAPPING; + _pathFriendlyURLPrivateUser = + _pathContext + _PRIVATE_USER_SERVLET_MAPPING; + _pathFriendlyURLPublic = _pathContext + _PUBLIC_GROUP_SERVLET_MAPPING; + _pathImage = _pathContext + PATH_IMAGE; + _pathMain = _pathContext + PATH_MAIN; + + // Groups + + String[] customSystemGroups = PropsUtil.getArray( + PropsKeys.SYSTEM_GROUPS); + + if ((customSystemGroups == null) || (customSystemGroups.length == 0)) { + _allSystemGroups = GroupConstants.SYSTEM_GROUPS; + } + else { + _allSystemGroups = ArrayUtil.append( + GroupConstants.SYSTEM_GROUPS, customSystemGroups); + } + + _sortedSystemGroups = new String[_allSystemGroups.length]; + + System.arraycopy( + _allSystemGroups, 0, _sortedSystemGroups, 0, + _allSystemGroups.length); + + Arrays.sort(_sortedSystemGroups, new StringComparator()); + + // Regular roles + + String[] customSystemRoles = PropsUtil.getArray(PropsKeys.SYSTEM_ROLES); + + if ((customSystemRoles == null) || (customSystemRoles.length == 0)) { + _allSystemRoles = RoleConstants.SYSTEM_ROLES; + } + else { + _allSystemRoles = ArrayUtil.append( + RoleConstants.SYSTEM_ROLES, customSystemRoles); + } + + _sortedSystemRoles = new String[_allSystemRoles.length]; + + System.arraycopy( + _allSystemRoles, 0, _sortedSystemRoles, 0, _allSystemRoles.length); + + Arrays.sort(_sortedSystemRoles, new StringComparator()); + + // Organization roles + + String[] customSystemOrganizationRoles = PropsUtil.getArray( + PropsKeys.SYSTEM_ORGANIZATION_ROLES); + + if ((customSystemOrganizationRoles == null) || + (customSystemOrganizationRoles.length == 0)) { + + _allSystemOrganizationRoles = + RoleConstants.SYSTEM_ORGANIZATION_ROLES; + } + else { + _allSystemOrganizationRoles = ArrayUtil.append( + RoleConstants.SYSTEM_ORGANIZATION_ROLES, + customSystemOrganizationRoles); + } + + _sortedSystemOrganizationRoles = + new String[_allSystemOrganizationRoles.length]; + + System.arraycopy( + _allSystemOrganizationRoles, 0, _sortedSystemOrganizationRoles, 0, + _allSystemOrganizationRoles.length); + + Arrays.sort(_sortedSystemOrganizationRoles, new StringComparator()); + + // Site roles + + String[] customSystemSiteRoles = PropsUtil.getArray( + PropsKeys.SYSTEM_SITE_ROLES); + + if ((customSystemSiteRoles == null) || + (customSystemSiteRoles.length == 0)) { + + _allSystemSiteRoles = RoleConstants.SYSTEM_SITE_ROLES; + } + else { + _allSystemSiteRoles = ArrayUtil.append( + RoleConstants.SYSTEM_SITE_ROLES, customSystemSiteRoles); + } + + _sortedSystemSiteRoles = new String[_allSystemSiteRoles.length]; + + System.arraycopy( + _allSystemSiteRoles, 0, _sortedSystemSiteRoles, 0, + _allSystemSiteRoles.length); + + Arrays.sort(_sortedSystemSiteRoles, new StringComparator()); + + // Authentication token ignore actions and tokens + + _authTokenIgnoreActions = SetUtil.fromArray( + PropsValues.AUTH_TOKEN_IGNORE_ACTIONS); + _authTokenIgnorePortlets = SetUtil.fromArray( + PropsValues.AUTH_TOKEN_IGNORE_PORTLETS); + + // Portlet add default resource check white list + + resetPortletAddDefaultResourceCheckWhitelist(); + resetPortletAddDefaultResourceCheckWhitelistActions(); + + // Reserved parameter names + + _reservedParams = new HashSet(); + + // Portal authentication + + _reservedParams.add("p_auth"); + _reservedParams.add("p_auth_secret"); + + // Portal layout + + _reservedParams.add("p_l_id"); + _reservedParams.add("p_l_reset"); + + // Portal portlet + + _reservedParams.add("p_p_auth"); + _reservedParams.add("p_p_id"); + _reservedParams.add("p_p_i_id"); + _reservedParams.add("p_p_lifecycle"); + _reservedParams.add("p_p_url_type"); + _reservedParams.add("p_p_state"); + _reservedParams.add("p_p_state_rcv"); // LPS-14144 + _reservedParams.add("p_p_mode"); + _reservedParams.add("p_p_resource_id"); + _reservedParams.add("p_p_cacheability"); + _reservedParams.add("p_p_width"); + _reservedParams.add("p_p_col_id"); + _reservedParams.add("p_p_col_pos"); + _reservedParams.add("p_p_col_count"); + _reservedParams.add("p_p_static"); + _reservedParams.add("p_p_isolated"); + + // Portal theme + + _reservedParams.add("p_t_lifecycle"); // LPS-14383 + + // Portal virtual layout + + _reservedParams.add("p_v_l_s_g_id"); // LPS-23010 + + // Portal outer portlet + + _reservedParams.add("p_o_p_id"); // LPS-12097 + + // Portal fragment + + _reservedParams.add("p_f_id"); + + // Portal journal article + + _reservedParams.add("p_j_a_id"); // LPS-16418 + + // Miscellaneous + + _reservedParams.add("saveLastPath"); + _reservedParams.add("scroll"); + } + + public void addPageDescription( + String description, HttpServletRequest request) { + + String requestDescription = (String)request.getAttribute( + WebKeys.PAGE_DESCRIPTION); + + if (requestDescription != null) { + description = requestDescription + StringPool.SPACE + description; + } + + request.setAttribute(WebKeys.PAGE_DESCRIPTION, description); + } + + public void addPageKeywords(String keywords, HttpServletRequest request) { + List requestKeywords = (List)request.getAttribute( + WebKeys.PAGE_KEYWORDS); + + if (requestKeywords == null) { + requestKeywords = new UniqueList(); + } + + String[] keywordsArray = StringUtil.split(keywords); + + for (String keyword : keywordsArray) { + if (!requestKeywords.contains(keyword.toLowerCase())) { + requestKeywords.add(keyword.toLowerCase()); + } + } + + request.setAttribute(WebKeys.PAGE_KEYWORDS, requestKeywords); + } + + public void addPageSubtitle(String subtitle, HttpServletRequest request) { + String requestSubtitle = (String)request.getAttribute( + WebKeys.PAGE_SUBTITLE); + + if (requestSubtitle != null) { + subtitle = requestSubtitle + StringPool.SPACE + subtitle; + } + + request.setAttribute(WebKeys.PAGE_SUBTITLE, subtitle); + } + + public void addPageTitle(String title, HttpServletRequest request) { + String requestTitle = (String)request.getAttribute(WebKeys.PAGE_TITLE); + + if (requestTitle != null) { + title = requestTitle + StringPool.SPACE + title; + } + + request.setAttribute(WebKeys.PAGE_TITLE, title); + } + + public void addPortalPortEventListener( + PortalPortEventListener portalPortEventListener) { + + if (!_portalPortEventListeners.contains(portalPortEventListener)) { + _portalPortEventListeners.add(portalPortEventListener); + } + } + + public void addPortletBreadcrumbEntry( + HttpServletRequest request, String title, String url) { + + addPortletBreadcrumbEntry(request, title, url, null); + } + + public void addPortletBreadcrumbEntry( + HttpServletRequest request, String title, String url, + Map data) { + + List breadcrumbEntries = + (List)request.getAttribute( + WebKeys.PORTLET_BREADCRUMBS); + + if (breadcrumbEntries == null) { + breadcrumbEntries = new ArrayList(); + + request.setAttribute( + WebKeys.PORTLET_BREADCRUMBS, breadcrumbEntries); + } + + BreadcrumbEntry breadcrumbEntry = new BreadcrumbEntry(); + + breadcrumbEntry.setData(data); + breadcrumbEntry.setTitle(title); + breadcrumbEntry.setURL(url); + + breadcrumbEntries.add(breadcrumbEntry); + } + + public void addPortletDefaultResource( + HttpServletRequest request, Portlet portlet) + throws PortalException, SystemException { + + ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( + WebKeys.THEME_DISPLAY); + + Layout layout = themeDisplay.getLayout(); + + addDefaultResource(themeDisplay, layout, portlet, true); + addDefaultResource(themeDisplay, layout, portlet, false); + } + + public void addPortletDefaultResource( + long companyId, Layout layout, Portlet portlet) + throws PortalException, SystemException { + + addDefaultResource(companyId, layout, portlet, true); + addDefaultResource(companyId, layout, portlet, false); + } + + public String addPreservedParameters( + ThemeDisplay themeDisplay, Layout layout, String url, + boolean doAsUser) { + + if (doAsUser) { + if (Validator.isNotNull(themeDisplay.getDoAsUserId())) { + url = HttpUtil.addParameter( + url, "doAsUserId", themeDisplay.getDoAsUserId()); + } + + if (Validator.isNotNull(themeDisplay.getDoAsUserLanguageId())) { + url = HttpUtil.addParameter( + url, "doAsUserLanguageId", + themeDisplay.getDoAsUserLanguageId()); + } + } + + if (layout.isTypeControlPanel()) { + if (themeDisplay.getDoAsGroupId() > 0) { + url = HttpUtil.addParameter( + url, "doAsGroupId", themeDisplay.getDoAsGroupId()); + } + + if (themeDisplay.getRefererPlid() != LayoutConstants.DEFAULT_PLID) { + url = HttpUtil.addParameter( + url, "refererPlid", themeDisplay.getRefererPlid()); + } + + if (Validator.isNotNull(themeDisplay.getControlPanelCategory())) { + url = HttpUtil.addParameter( + url, "controlPanelCategory", + themeDisplay.getControlPanelCategory()); + } + } + + return url; + } + + public String addPreservedParameters( + ThemeDisplay themeDisplay, String url) { + + return addPreservedParameters( + themeDisplay, themeDisplay.getLayout(), url, true); + } + + public void clearRequestParameters(RenderRequest renderRequest) { + RenderRequestImpl renderRequestImpl = (RenderRequestImpl)renderRequest; + + if (renderRequestImpl.isTriggeredByActionURL()) { + Map renderParameters = + renderRequestImpl.getRenderParameters(); + + renderParameters.clear(); + } + } + + public void copyRequestParameters( + ActionRequest actionRequest, ActionResponse actionResponse) { + + if (actionResponse instanceof StateAwareResponseImpl) { + StateAwareResponseImpl stateAwareResponseImpl = + (StateAwareResponseImpl)actionResponse; + + if (stateAwareResponseImpl.getRedirectLocation() != null) { + if (_log.isDebugEnabled()) { + _log.debug( + "Cannot copy parameters on a redirected " + + "StateAwareResponseImpl"); + } + + return; + } + } + + ActionResponseImpl actionResponseImpl = + (ActionResponseImpl)actionResponse; + + Map renderParameters = + actionResponseImpl.getRenderParameterMap(); + + actionResponse.setRenderParameter("p_p_lifecycle", "1"); + + Enumeration enu = actionRequest.getParameterNames(); + + while (enu.hasMoreElements()) { + String param = enu.nextElement(); + String[] values = actionRequest.getParameterValues(param); + + if (renderParameters.get( + actionResponseImpl.getNamespace() + param) == null) { + + actionResponse.setRenderParameter(param, values); + } + } + } + + public String escapeRedirect(String url) { + if (Validator.isNull(url) || !HttpUtil.hasDomain(url)) { + return url; + } + + String domain = HttpUtil.getDomain(url); + + int pos = -1; + + if ((pos = domain.indexOf(CharPool.COLON)) != -1) { + domain = domain.substring(0, pos); + } + + try { + Company company = CompanyLocalServiceUtil.fetchCompanyByVirtualHost( + domain); + + if (company != null) { + return url; + } + } + catch (Exception e) { + } + + try { + LayoutSet layoutSet = LayoutSetLocalServiceUtil.fetchLayoutSet( + domain); + + if (layoutSet != null) { + return url; + } + } + catch (Exception e) { + } + + try { + String securityMode = PropsValues.REDIRECT_URL_SECURITY_MODE; + + if (securityMode.equals("domain")) { + String[] allowedDomains = + PropsValues.REDIRECT_URL_DOMAINS_ALLOWED; + + if ((allowedDomains.length > 0) && + !ArrayUtil.contains(allowedDomains, domain)) { + + if (_log.isDebugEnabled()) { + _log.debug("Redirect URL " + url + " is not allowed"); + } + + url = null; + } + } + else if (securityMode.equals("ip")) { + String[] allowedIps = PropsValues.REDIRECT_URL_IPS_ALLOWED; + + InetAddress inetAddress = InetAddress.getByName(domain); + + if ((allowedIps.length > 0) && + !ArrayUtil.contains( + allowedIps, inetAddress.getHostAddress())) { + + String serverIp = getComputerAddress(); + + if (!serverIp.equals(inetAddress.getHostAddress()) || + !ArrayUtil.contains(allowedIps, "SERVER_IP")) { + + if (_log.isDebugEnabled()) { + _log.debug( + "Redirect URL " + url + " is not allowed"); + } + + url = null; + } + } + } + } + catch (UnknownHostException uhe) { + if (_log.isDebugEnabled()) { + _log.debug("Unable to determine IP for redirect URL " + url); + } + + url = null; + } + + return url; + } + + public String generateRandomKey(HttpServletRequest request, String input) { + ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( + WebKeys.THEME_DISPLAY); + + if (themeDisplay.isLifecycleResource() || + themeDisplay.isStateExclusive()) { + + return PwdGenerator.getPassword(PwdGenerator.KEY3, 4); + } + else { + return DeterminateKeyGenerator.generate(input); + } + } + + public String getActualURL( + long groupId, boolean privateLayout, String mainPath, + String friendlyURL, Map params, + Map requestContext) + throws PortalException, SystemException { + + String actualURL = null; + + if (friendlyURL != null) { + if (friendlyURL.startsWith( + JournalArticleConstants.CANONICAL_URL_SEPARATOR)) { + + try { + actualURL = getJournalArticleActualURL( + groupId, mainPath, friendlyURL, params, requestContext); + } + catch (Exception e) { + friendlyURL = null; + } + } + else if (friendlyURL.startsWith( + VirtualLayoutConstants.CANONICAL_URL_SEPARATOR)) { + + try { + actualURL = getVirtualLayoutActualURL( + groupId, privateLayout, mainPath, friendlyURL, params, + requestContext); + } + catch (Exception e) { + friendlyURL = null; + } + } + } + + if (actualURL == null) { + actualURL = getLayoutActualURL( + groupId, privateLayout, mainPath, friendlyURL, params, + requestContext); + } + + return actualURL; + } + + public Locale[] getAlternateLocales(HttpServletRequest request) + throws SystemException, PortalException { + + Locale[] availableLocales = LanguageUtil.getAvailableLocales(); + + long mainJournalArticleId = ParamUtil.getLong(request, "p_j_a_id"); + + if (mainJournalArticleId > 0) { + JournalArticle mainJournalArticle = + JournalArticleLocalServiceUtil.getJournalArticle( + mainJournalArticleId); + + if (mainJournalArticle != null) { + String[] articleLocales = + mainJournalArticle.getAvailableLocales(); + + if (articleLocales.length > 1) { + Locale[] alternateLocales = new Locale[ + availableLocales.length - articleLocales.length]; + + int i = 0; + + for (Locale locale : availableLocales) { + if (!ArrayUtil.contains( + articleLocales, LocaleUtil.toLanguageId(locale))) { + + alternateLocales[i] = locale; + + i++; + } + } + + return alternateLocales; + } + } + } + + return availableLocales; + } + + public String getAlternateURL( + String canonicalURL, ThemeDisplay themeDisplay, Locale locale) { + + LayoutSet layoutSet = themeDisplay.getLayoutSet(); + + String virtualHost = null; + + if (Validator.isNotNull(layoutSet.getVirtualHostname())) { + virtualHost = layoutSet.getVirtualHostname(); + } + else { + Company company = themeDisplay.getCompany(); + + virtualHost = company.getVirtualHostname(); + } + + String i18nPath = buildI18NPath(locale); + + if (Validator.isNull(virtualHost)) { + return canonicalURL.replaceFirst( + _PUBLIC_GROUP_SERVLET_MAPPING, + i18nPath.concat(_PUBLIC_GROUP_SERVLET_MAPPING)); + } + + // www.liferay.com:8080/page to www.liferay.com:8080/es/page + + int pos = canonicalURL.indexOf(virtualHost); + + if (pos > 0) { + pos += virtualHost.length(); + + pos = canonicalURL.indexOf(CharPool.SLASH, pos); + + if ((pos > 0) && (pos < canonicalURL.length())) { + return canonicalURL.substring(0, pos).concat( + i18nPath).concat(canonicalURL.substring(pos)); + } + } + + return canonicalURL.concat(i18nPath); + } + + public Set getAuthTokenIgnoreActions() { + return _authTokenIgnoreActions; + } + + public Set getAuthTokenIgnorePortlets() { + return _authTokenIgnorePortlets; + } + + public BaseModel getBaseModel(Resource resource) + throws PortalException, SystemException { + + ResourceCode resourceCode = + ResourceCodeLocalServiceUtil.getResourceCode(resource.getCodeId()); + + String modelName = resourceCode.getName(); + String primKey = resource.getPrimKey(); + + return getBaseModel(modelName, primKey); + } + + public BaseModel getBaseModel(ResourcePermission resourcePermission) + throws PortalException, SystemException { + + String modelName = resourcePermission.getName(); + String primKey = resourcePermission.getPrimKey(); + + return getBaseModel(modelName, primKey); + } + + public BaseModel getBaseModel(String modelName, String primKey) + throws PortalException, SystemException { + + if (!modelName.contains(".model.")) { + return null; + } + + String[] parts = StringUtil.split(modelName, CharPool.PERIOD); + + if ((parts.length <= 2) || !parts[parts.length - 2].equals("model")) { + return null; + } + + parts[parts.length - 2] = "service"; + + String serviceName = + StringUtil.merge(parts, StringPool.PERIOD) + "LocalServiceUtil"; + String methodName = "get" + parts[parts.length - 1]; + + Method method = null; + + try { + Class serviceUtil = Class.forName(serviceName); + + if (Validator.isNumber(primKey)) { + method = serviceUtil.getMethod( + methodName, new Class[] {Long.TYPE}); + + return (BaseModel)method.invoke(null, new Long(primKey)); + } + else { + method = serviceUtil.getMethod( + methodName, new Class[] {String.class}); + + return (BaseModel)method.invoke(null, primKey); + } + } + catch (Exception e) { + Throwable cause = e.getCause(); + + if (cause instanceof PortalException) { + throw (PortalException)cause; + } + else if (cause instanceof SystemException) { + throw (SystemException)cause; + } + else { + throw new SystemException(cause); + } + } + } + + public long getBasicAuthUserId(HttpServletRequest request) + throws PortalException, SystemException { + + long companyId = PortalInstances.getCompanyId(request); + + return getBasicAuthUserId(request, companyId); + } + + public long getBasicAuthUserId(HttpServletRequest request, long companyId) + throws PortalException, SystemException { + + long userId = 0; + + String authorizationHeader = request.getHeader( + HttpHeaders.AUTHORIZATION); + + if (Validator.isNull(authorizationHeader)) { + return userId; + } + + String[] authorizationArray = authorizationHeader.split("\\s+"); + + String authorization = authorizationArray[0]; + String credentials = new String(Base64.decode(authorizationArray[1])); + + if (!authorization.equalsIgnoreCase(HttpServletRequest.BASIC_AUTH)) { + return userId; + } + + String[] loginAndPassword = StringUtil.split( + credentials, CharPool.COLON); + + String login = loginAndPassword[0].trim(); + + String password = null; + + if (loginAndPassword.length > 1) { + password = loginAndPassword[1].trim(); + } + + // Strip @uid and @sn for backwards compatibility + + if (login.endsWith("@uid")) { + int pos = login.indexOf("@uid"); + + login = login.substring(0, pos); + } + else if (login.endsWith("@sn")) { + int pos = login.indexOf("@sn"); + + login = login.substring(0, pos); + } + + try { + userId = LoginUtil.getAuthenticatedUserId( + request, login, password, null); + } + catch (AuthException ae) { + } + + return userId; + } + + public String getCanonicalURL( + String completeURL, ThemeDisplay themeDisplay, Layout layout) + throws PortalException, SystemException { + + completeURL = removeRedirectParameter(completeURL); + + String parametersURL = StringPool.BLANK; + + int pos = completeURL.indexOf(Portal.FRIENDLY_URL_SEPARATOR); + + if (pos == -1) { + pos = completeURL.indexOf(StringPool.QUESTION); + } + + String groupFriendlyURL = completeURL; + + if (pos != -1) { + groupFriendlyURL = completeURL.substring(0, pos); + + parametersURL = completeURL.substring(pos); + } + + if (layout == null) { + layout = themeDisplay.getLayout(); + } + + String layoutFriendlyURL = StringPool.BLANK; + + if ((groupFriendlyURL.contains(layout.getFriendlyURL()) || + groupFriendlyURL.contains( + StringPool.SLASH + layout.getLayoutId())) && + (!layout.isFirstParent() || Validator.isNotNull(parametersURL))) { + + layoutFriendlyURL = layout.getFriendlyURL(); + } + + Group group = layout.getGroup(); + + groupFriendlyURL = getGroupFriendlyURL( + group, layout.isPrivateLayout(), themeDisplay, true); + + return groupFriendlyURL.concat(layoutFriendlyURL).concat(parametersURL); + } + + /** + * @deprecated {@link #getCDNHost(boolean)} + */ + public String getCDNHost() { + long companyId = CompanyThreadLocal.getCompanyId(); + + return getCDNHostHttp(companyId); + } + + public String getCDNHost(boolean secure) { + long companyId = CompanyThreadLocal.getCompanyId(); + + if (secure) { + return getCDNHostHttps(companyId); + } + else { + return getCDNHostHttp(companyId); + } + } + + public String getCDNHost(HttpServletRequest request) + throws PortalException, SystemException { + + String cdnHost = null; + + Company company = getCompany(request); + + if (request.isSecure()) { + cdnHost = getCDNHostHttps(company.getCompanyId()); + } + else { + cdnHost = getCDNHostHttp(company.getCompanyId()); + } + + return ParamUtil.getString(request, "cdn_host", cdnHost); + } + + public String getCDNHostHttp(long companyId) { + String cdnHostHttp = _cdnHostHttpMap.get(companyId); + + if (cdnHostHttp != null) { + return cdnHostHttp; + } + + try { + cdnHostHttp = PrefsPropsUtil.getString( + companyId, PropsKeys.CDN_HOST_HTTP, PropsValues.CDN_HOST_HTTP); + } + catch (Exception e) { + } + + if ((cdnHostHttp == null) || cdnHostHttp.startsWith("${")) { + cdnHostHttp = StringPool.BLANK; + } + + _cdnHostHttpMap.put(companyId, cdnHostHttp); + + return cdnHostHttp; + } + + public String getCDNHostHttps(long companyId) { + String cdnHostHttps = _cdnHostHttpsMap.get(companyId); + + if (cdnHostHttps != null) { + return cdnHostHttps; + } + + try { + cdnHostHttps = PrefsPropsUtil.getString( + companyId, PropsKeys.CDN_HOST_HTTPS, + PropsValues.CDN_HOST_HTTPS); + } + catch (SystemException e) { + } + + if ((cdnHostHttps == null) || cdnHostHttps.startsWith("${")) { + cdnHostHttps = StringPool.BLANK; + } + + _cdnHostHttpsMap.put(companyId, cdnHostHttps); + + return cdnHostHttps; + } + + public String getClassName(long classNameId) { + try { + ClassName className = ClassNameLocalServiceUtil.getClassName( + classNameId); + + return className.getValue(); + } + catch (Exception e) { + throw new RuntimeException( + "Unable to get class name from id " + classNameId); + } + } + + public long getClassNameId(Class clazz) { + return ClassNameLocalServiceUtil.getClassNameId(clazz); + } + + public long getClassNameId(String value) { + return ClassNameLocalServiceUtil.getClassNameId(value); + } + + public String getClassNamePortletId(String className) { + String portletId = StringPool.BLANK; + + if (className.startsWith("com.liferay.portlet.blogs")) { + portletId = PortletKeys.BLOGS; + } + else if (className.startsWith("com.liferay.portlet.bookmarks")) { + portletId = PortletKeys.BOOKMARKS; + } + else if (className.startsWith("com.liferay.portlet.calendar")) { + portletId = PortletKeys.CALENDAR; + } + else if (className.startsWith("com.liferay.portlet.documentlibrary")) { + portletId = PortletKeys.DOCUMENT_LIBRARY; + } + else if (className.startsWith("com.liferay.portlet.imagegallery")) { + portletId = PortletKeys.MEDIA_GALLERY_DISPLAY; + } + else if (className.startsWith("com.liferay.portlet.journal")) { + portletId = PortletKeys.JOURNAL; + } + else if (className.startsWith("com.liferay.portlet.messageboards")) { + portletId = PortletKeys.MESSAGE_BOARDS; + } + else if (className.startsWith("com.liferay.portlet.wiki")) { + portletId = PortletKeys.WIKI; + } + + return portletId; + } + + public Company getCompany(HttpServletRequest request) + throws PortalException, SystemException { + + long companyId = getCompanyId(request); + + if (companyId <= 0) { + return null; + } + + Company company = (Company)request.getAttribute(WebKeys.COMPANY); + + if (company == null) { + + // LEP-5994 + + try { + company = CompanyLocalServiceUtil.getCompanyById(companyId); + } + catch (NoSuchCompanyException nsce) { + company = CompanyLocalServiceUtil.getCompanyById( + PortalInstances.getDefaultCompanyId()); + } + + request.setAttribute(WebKeys.COMPANY, company); + } + + return company; + } + + public Company getCompany(PortletRequest portletRequest) + throws PortalException, SystemException { + + return getCompany(getHttpServletRequest(portletRequest)); + } + + public long getCompanyId(HttpServletRequest request) { + return PortalInstances.getCompanyId(request); + } + + public long getCompanyId(PortletRequest portletRequest) { + return getCompanyId(getHttpServletRequest(portletRequest)); + } + + public long[] getCompanyIds() { + return PortalInstances.getCompanyIds(); + } + + public String getComputerAddress() { + return _computerAddress; + } + + public String getComputerName() { + return _computerName; + } + + public String getControlPanelCategory( + String portletId, ThemeDisplay themeDisplay) + throws SystemException { + + for (String category : PortletCategoryKeys.ALL) { + List portlets = getControlPanelPortlets( + category, themeDisplay); + + for (Portlet portlet : portlets) { + if (portlet.getPortletId().equals(portletId)) { + return category; + } + } + } + + return StringPool.BLANK; + } + + public String getControlPanelFullURL( + long scopeGroupId, String ppid, Map params) + throws PortalException, SystemException { + + StringBundler sb = new StringBundler(6); + + Group group = GroupLocalServiceUtil.getGroup(scopeGroupId); + + Company company = CompanyLocalServiceUtil.getCompany( + group.getCompanyId()); + + sb.append( + getPortalURL( + company.getVirtualHostname(), getPortalPort(false), false)); + sb.append(getPathFriendlyURLPrivateGroup()); + sb.append(GroupConstants.CONTROL_PANEL_FRIENDLY_URL); + sb.append(PropsValues.CONTROL_PANEL_LAYOUT_FRIENDLY_URL); + + if (params != null) { + params = new HashMap(params); + } + else { + params = new HashMap(); + } + + params.put("p_p_id", new String[] {ppid}); + params.put("p_p_lifecycle", new String[] {"0"}); + params.put( + "p_p_state", new String[] {WindowState.MAXIMIZED.toString()}); + params.put("p_p_mode", new String[] {PortletMode.VIEW.toString()}); + + sb.append(HttpUtil.parameterMapToString(params, true)); + + return sb.toString(); + } + + public Set getControlPanelPortlets(long companyId, String category) + throws SystemException { + + Set portletsSet = new TreeSet( + new PortletControlPanelWeightComparator()); + + List portletsList = PortletLocalServiceUtil.getPortlets( + companyId); + + for (Portlet portlet : portletsList) { + if (category.equals(portlet.getControlPanelEntryCategory())) { + portletsSet.add(portlet); + } + } + + return portletsSet; + } + + public List getControlPanelPortlets( + String category, ThemeDisplay themeDisplay) + throws SystemException { + + Set portlets = getControlPanelPortlets( + themeDisplay.getCompanyId(), category); + + return filterControlPanelPortlets(portlets, category, themeDisplay); + } + + public String getCreateAccountURL( + HttpServletRequest request, ThemeDisplay themeDisplay) + throws Exception { + + if (Validator.isNull(PropsValues.COMPANY_SECURITY_STRANGERS_URL)) { + PortletURL createAccountURL = PortletURLFactoryUtil.create( + request, PortletKeys.LOGIN, themeDisplay.getPlid(), + PortletRequest.RENDER_PHASE); + + createAccountURL.setWindowState(WindowState.MAXIMIZED); + createAccountURL.setPortletMode(PortletMode.VIEW); + + createAccountURL.setParameter("saveLastPath", "0"); + createAccountURL.setParameter( + "struts_action", "/login/create_account"); + + return createAccountURL.toString(); + } + + try { + Layout layout = LayoutLocalServiceUtil.getFriendlyURLLayout( + themeDisplay.getScopeGroupId(), false, + PropsValues.COMPANY_SECURITY_STRANGERS_URL); + + return PortalUtil.getLayoutURL(layout, themeDisplay); + } + catch (NoSuchLayoutException nsle) { + } + + return StringPool.BLANK; + } + + public String getCurrentCompleteURL(HttpServletRequest request) { + String currentCompleteURL = (String)request.getAttribute( + WebKeys.CURRENT_COMPLETE_URL); + + if (currentCompleteURL == null) { + currentCompleteURL = HttpUtil.getCompleteURL(request); + + request.setAttribute( + WebKeys.CURRENT_COMPLETE_URL, currentCompleteURL); + } + + return currentCompleteURL; + } + + public String getCurrentURL(HttpServletRequest request) { + String currentURL = (String)request.getAttribute(WebKeys.CURRENT_URL); + + if (currentURL != null) { + return currentURL; + } + + currentURL = ParamUtil.getString(request, "currentURL"); + + if (Validator.isNull(currentURL)) { + currentURL = HttpUtil.getCompleteURL(request); + + if ((Validator.isNotNull(currentURL)) && + (currentURL.indexOf(_J_SECURITY_CHECK) == -1)) { + + currentURL = currentURL.substring( + currentURL.indexOf(Http.PROTOCOL_DELIMITER) + + Http.PROTOCOL_DELIMITER.length()); + + currentURL = currentURL.substring( + currentURL.indexOf(CharPool.SLASH)); + } + + if (Validator.isNotNull(currentURL) && + FacebookUtil.isFacebook(currentURL)) { + + String[] facebookData = FacebookUtil.getFacebookData(request); + + currentURL = + FacebookUtil.FACEBOOK_APPS_URL + facebookData[0] + + facebookData[2]; + } + } + + if (Validator.isNull(currentURL)) { + currentURL = getPathMain(); + } + + request.setAttribute(WebKeys.CURRENT_URL, currentURL); + + return currentURL; + } + + public String getCurrentURL(PortletRequest portletRequest) { + return (String)portletRequest.getAttribute(WebKeys.CURRENT_URL); + } + + public String getCustomSQLFunctionIsNotNull() { + return PropsValues.CUSTOM_SQL_FUNCTION_ISNOTNULL; + } + + public String getCustomSQLFunctionIsNull() { + return PropsValues.CUSTOM_SQL_FUNCTION_ISNULL; + } + + public Date getDate(int month, int day, int year) { + try { + return getDate(month, day, year, null); + } + catch (PortalException pe) { + throw new RuntimeException(); + } + } + + public Date getDate( + int month, int day, int year, int hour, int min, PortalException pe) + throws PortalException { + + return getDate(month, day, year, hour, min, null, pe); + } + + public Date getDate( + int month, int day, int year, int hour, int min, TimeZone timeZone, + PortalException pe) + throws PortalException { + + if (!Validator.isGregorianDate(month, day, year)) { + if (pe != null) { + throw pe; + } + else { + return null; + } + } + else { + Calendar cal = null; + + if (timeZone == null) { + cal = CalendarFactoryUtil.getCalendar(); + } + else { + cal = CalendarFactoryUtil.getCalendar(timeZone); + } + + if ((hour == -1) || (min == -1)) { + cal.set(year, month, day, 0, 0, 0); + } + else { + cal.set(year, month, day, hour, min, 0); + } + + cal.set(Calendar.MILLISECOND, 0); + + Date date = cal.getTime(); + + /*if (timeZone != null && + cal.before(CalendarFactoryUtil.getCalendar(timeZone))) { + + throw pe; + }*/ + + return date; + } + } + + public Date getDate(int month, int day, int year, PortalException pe) + throws PortalException { + + return getDate(month, day, year, null, pe); + } + + public Date getDate( + int month, int day, int year, TimeZone timeZone, PortalException pe) + throws PortalException { + + return getDate(month, day, year, -1, -1, timeZone, pe); + } + + public long getDefaultCompanyId() { + return PortalInstances.getDefaultCompanyId(); + } + + public long getDigestAuthUserId(HttpServletRequest request) + throws PortalException, SystemException { + + long userId = 0; + + String authorizationHeader = request.getHeader( + HttpHeaders.AUTHORIZATION); + + if (Validator.isNull(authorizationHeader) || + !authorizationHeader.startsWith("Digest ")) { + + return userId; + } + + authorizationHeader = authorizationHeader.substring("Digest ".length()); + authorizationHeader = StringUtil.replace( + authorizationHeader, CharPool.COMMA, CharPool.NEW_LINE); + + UnicodeProperties authorizationProperties = new UnicodeProperties(); + + authorizationProperties.fastLoad(authorizationHeader); + + String username = StringUtil.unquote( + authorizationProperties.getProperty("username")); + String realm = StringUtil.unquote( + authorizationProperties.getProperty("realm")); + String nonce = StringUtil.unquote( + authorizationProperties.getProperty("nonce")); + String uri = StringUtil.unquote( + authorizationProperties.getProperty("uri")); + String response = StringUtil.unquote( + authorizationProperties.getProperty("response")); + + if (Validator.isNull(username) || Validator.isNull(realm) || + Validator.isNull(nonce) || Validator.isNull(uri) || + Validator.isNull(response)) { + + return userId; + } + + if (!realm.equals(PORTAL_REALM) || + !uri.equals(request.getRequestURI())) { + + return userId; + } + + if (!NonceUtil.verify(nonce)) { + return userId; + } + + long companyId = PortalInstances.getCompanyId(request); + + userId = UserLocalServiceUtil.authenticateForDigest( + companyId, username, realm, nonce, request.getMethod(), uri, + response); + + return userId; + } + + public String getEmailFromAddress( + PortletPreferences preferences, long companyId, String defaultValue) + throws SystemException { + + if (Validator.isNull(defaultValue)) { + defaultValue = PrefsPropsUtil.getString( + companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS); + } + + return preferences.getValue("emailFromAddress", defaultValue); + } + + public String getEmailFromName( + PortletPreferences preferences, long companyId, String defaultValue) + throws SystemException { + + if (Validator.isNull(defaultValue)) { + defaultValue = PrefsPropsUtil.getString( + companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME); + } + + return preferences.getValue("emailFromName", defaultValue); + } + + public Map getExpandoBridgeAttributes( + ExpandoBridge expandoBridge, PortletRequest portletRequest) + throws PortalException, SystemException { + + Map attributes = + new HashMap(); + + List names = new ArrayList(); + + Enumeration enu = portletRequest.getParameterNames(); + + while (enu.hasMoreElements()) { + String param = enu.nextElement(); + + if (param.indexOf("ExpandoAttributeName--") != -1) { + String name = ParamUtil.getString(portletRequest, param); + + names.add(name); + } + } + + for (String name : names) { + int type = expandoBridge.getAttributeType(name); + + UnicodeProperties properties = expandoBridge.getAttributeProperties( + name); + + String displayType = GetterUtil.getString( + properties.getProperty( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE), + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX); + + Serializable value = getExpandoValue( + portletRequest, "ExpandoAttribute--" + name + "--", type, + displayType); + + attributes.put(name, value); + } + + return attributes; + } + + public Map getExpandoBridgeAttributes( + ExpandoBridge expandoBridge, + UploadPortletRequest uploadPortletRequest) + throws PortalException, SystemException { + + Map attributes = + new HashMap(); + + List names = new ArrayList(); + + Enumeration enu = uploadPortletRequest.getParameterNames(); + + while (enu.hasMoreElements()) { + String param = enu.nextElement(); + + if (param.indexOf("ExpandoAttributeName--") != -1) { + String name = ParamUtil.getString(uploadPortletRequest, param); + + names.add(name); + } + } + + for (String name : names) { + int type = expandoBridge.getAttributeType(name); + + UnicodeProperties properties = expandoBridge.getAttributeProperties( + name); + + String displayType = GetterUtil.getString( + properties.getProperty( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE), + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX); + + Serializable value = getExpandoValue( + uploadPortletRequest, "ExpandoAttribute--" + name + "--", type, + displayType); + + attributes.put(name, value); + } + + return attributes; + } + + public Serializable getExpandoValue( + PortletRequest portletRequest, String name, int type, + String displayType) + throws PortalException, SystemException { + + Serializable value = null; + + if (type == ExpandoColumnConstants.BOOLEAN) { + value = ParamUtil.getBoolean(portletRequest, name); + } + else if (type == ExpandoColumnConstants.BOOLEAN_ARRAY) { + } + else if (type == ExpandoColumnConstants.DATE) { + int valueDateMonth = ParamUtil.getInteger( + portletRequest, name + "Month"); + int valueDateDay = ParamUtil.getInteger( + portletRequest, name + "Day"); + int valueDateYear = ParamUtil.getInteger( + portletRequest, name + "Year"); + int valueDateHour = ParamUtil.getInteger( + portletRequest, name + "Hour"); + int valueDateMinute = ParamUtil.getInteger( + portletRequest, name + "Minute"); + int valueDateAmPm = ParamUtil.getInteger( + portletRequest, name + "AmPm"); + + if (valueDateAmPm == Calendar.PM) { + valueDateHour += 12; + } + + TimeZone timeZone = null; + + User user = getUser(portletRequest); + + if (user != null) { + timeZone = user.getTimeZone(); + } + + value = getDate( + valueDateMonth, valueDateDay, valueDateYear, valueDateHour, + valueDateMinute, timeZone, new ValueDataException()); + } + else if (type == ExpandoColumnConstants.DATE_ARRAY) { + } + else if (type == ExpandoColumnConstants.DOUBLE) { + value = ParamUtil.getDouble(portletRequest, name); + } + else if (type == ExpandoColumnConstants.DOUBLE_ARRAY) { + String[] values = portletRequest.getParameterValues(name); + + if (displayType.equals( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { + + values = StringUtil.splitLines(values[0]); + } + + value = GetterUtil.getDoubleValues(values); + } + else if (type == ExpandoColumnConstants.FLOAT) { + value = ParamUtil.getFloat(portletRequest, name); + } + else if (type == ExpandoColumnConstants.FLOAT_ARRAY) { + String[] values = portletRequest.getParameterValues(name); + + if (displayType.equals( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { + + values = StringUtil.splitLines(values[0]); + } + + value = GetterUtil.getFloatValues(values); + } + else if (type == ExpandoColumnConstants.INTEGER) { + value = ParamUtil.getInteger(portletRequest, name); + } + else if (type == ExpandoColumnConstants.INTEGER_ARRAY) { + String[] values = portletRequest.getParameterValues(name); + + if (displayType.equals( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { + + values = StringUtil.splitLines(values[0]); + } + + value = GetterUtil.getIntegerValues(values); + } + else if (type == ExpandoColumnConstants.LONG) { + value = ParamUtil.getLong(portletRequest, name); + } + else if (type == ExpandoColumnConstants.LONG_ARRAY) { + String[] values = portletRequest.getParameterValues(name); + + if (displayType.equals( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { + + values = StringUtil.splitLines(values[0]); + } + + value = GetterUtil.getLongValues(values); + } + else if (type == ExpandoColumnConstants.SHORT) { + value = ParamUtil.getShort(portletRequest, name); + } + else if (type == ExpandoColumnConstants.SHORT_ARRAY) { + String[] values = portletRequest.getParameterValues(name); + + if (displayType.equals( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { + + values = StringUtil.splitLines(values[0]); + } + + value = GetterUtil.getShortValues(values); + } + else if (type == ExpandoColumnConstants.STRING_ARRAY) { + value = portletRequest.getParameterValues(name); + } + else { + value = ParamUtil.getString(portletRequest, name); + } + + return value; + } + + public Serializable getExpandoValue( + UploadPortletRequest uploadPortletRequest, String name, int type, + String displayType) + throws PortalException, SystemException { + + Serializable value = null; + + if (type == ExpandoColumnConstants.BOOLEAN) { + value = ParamUtil.getBoolean(uploadPortletRequest, name); + } + else if (type == ExpandoColumnConstants.BOOLEAN_ARRAY) { + } + else if (type == ExpandoColumnConstants.DATE) { + int valueDateMonth = ParamUtil.getInteger( + uploadPortletRequest, name + "Month"); + int valueDateDay = ParamUtil.getInteger( + uploadPortletRequest, name + "Day"); + int valueDateYear = ParamUtil.getInteger( + uploadPortletRequest, name + "Year"); + int valueDateHour = ParamUtil.getInteger( + uploadPortletRequest, name + "Hour"); + int valueDateMinute = ParamUtil.getInteger( + uploadPortletRequest, name + "Minute"); + int valueDateAmPm = ParamUtil.getInteger( + uploadPortletRequest, name + "AmPm"); + + if (valueDateAmPm == Calendar.PM) { + valueDateHour += 12; + } + + TimeZone timeZone = null; + + User user = getUser(uploadPortletRequest); + + if (user != null) { + timeZone = user.getTimeZone(); + } + + value = getDate( + valueDateMonth, valueDateDay, valueDateYear, valueDateHour, + valueDateMinute, timeZone, new ValueDataException()); + } + else if (type == ExpandoColumnConstants.DATE_ARRAY) { + } + else if (type == ExpandoColumnConstants.DOUBLE) { + value = ParamUtil.getDouble(uploadPortletRequest, name); + } + else if (type == ExpandoColumnConstants.DOUBLE_ARRAY) { + String[] values = uploadPortletRequest.getParameterValues(name); + + if (displayType.equals( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { + + values = StringUtil.splitLines(values[0]); + } + + value = GetterUtil.getDoubleValues(values); + } + else if (type == ExpandoColumnConstants.FLOAT) { + value = ParamUtil.getFloat(uploadPortletRequest, name); + } + else if (type == ExpandoColumnConstants.FLOAT_ARRAY) { + String[] values = uploadPortletRequest.getParameterValues(name); + + if (displayType.equals( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { + + values = StringUtil.splitLines(values[0]); + } + + value = GetterUtil.getFloatValues(values); + } + else if (type == ExpandoColumnConstants.INTEGER) { + value = ParamUtil.getInteger(uploadPortletRequest, name); + } + else if (type == ExpandoColumnConstants.INTEGER_ARRAY) { + String[] values = uploadPortletRequest.getParameterValues(name); + + if (displayType.equals( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { + + values = StringUtil.splitLines(values[0]); + } + + value = GetterUtil.getIntegerValues(values); + } + else if (type == ExpandoColumnConstants.LONG) { + value = ParamUtil.getLong(uploadPortletRequest, name); + } + else if (type == ExpandoColumnConstants.LONG_ARRAY) { + String[] values = uploadPortletRequest.getParameterValues(name); + + if (displayType.equals( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { + + values = StringUtil.splitLines(values[0]); + } + + value = GetterUtil.getLongValues(values); + } + else if (type == ExpandoColumnConstants.SHORT) { + value = ParamUtil.getShort(uploadPortletRequest, name); + } + else if (type == ExpandoColumnConstants.SHORT_ARRAY) { + String[] values = uploadPortletRequest.getParameterValues(name); + + if (displayType.equals( + ExpandoColumnConstants.PROPERTY_DISPLAY_TYPE_TEXT_BOX)) { + + values = StringUtil.splitLines(values[0]); + } + + value = GetterUtil.getShortValues(values); + } + else if (type == ExpandoColumnConstants.STRING_ARRAY) { + value = uploadPortletRequest.getParameterValues(name); + } + else { + value = ParamUtil.getString(uploadPortletRequest, name); + } + + return value; + } + + public String getFacebookURL( + Portlet portlet, String facebookCanvasPageURL, + ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + String facebookURL = getServletURL( + portlet, FacebookUtil.FACEBOOK_SERVLET_PATH + facebookCanvasPageURL, + themeDisplay); + + if (!facebookURL.endsWith(StringPool.SLASH)) { + facebookURL += StringPool.SLASH; + } + + return facebookURL; + } + + public String getFirstPageLayoutTypes(PageContext pageContext) { + StringBundler sb = new StringBundler(); + + for (String type : PropsValues.LAYOUT_TYPES) { + if (isLayoutFirstPageable(type)) { + sb.append( + LanguageUtil.get(pageContext, "layout.types." + type)); + sb.append(StringPool.COMMA); + sb.append(StringPool.SPACE); + } + } + + if (sb.index() >= 2) { + sb.setIndex(sb.index() - 2); + } + + return sb.toString(); + } + + public String getGlobalLibDir() { + return PropsValues.LIFERAY_LIB_GLOBAL_DIR; + } + + public String getGoogleGadgetURL(Portlet portlet, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getServletURL( + portlet, PropsValues.GOOGLE_GADGET_SERVLET_MAPPING, themeDisplay); + } + + public String getGroupFriendlyURL( + Group group, boolean privateLayoutSet, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getGroupFriendlyURL( + group, privateLayoutSet, themeDisplay, false); + } + + public String[] getGroupPermissions(HttpServletRequest request) { + return request.getParameterValues("groupPermissions"); + } + + public String[] getGroupPermissions(PortletRequest portletRequest) { + return portletRequest.getParameterValues("groupPermissions"); + } + + public String[] getGuestPermissions(HttpServletRequest request) { + return request.getParameterValues("guestPermissions"); + } + + public String[] getGuestPermissions(PortletRequest portletRequest) { + return portletRequest.getParameterValues("guestPermissions"); + } + + public String getHomeURL(HttpServletRequest request) + throws PortalException, SystemException { + + String portalURL = getPortalURL(request); + + return portalURL + _pathContext + getRelativeHomeURL(request); + } + + public String getHost(HttpServletRequest request) { + request = getOriginalServletRequest(request); + + String host = request.getHeader("Host"); + + if (host != null) { + host = host.trim().toLowerCase(); + + int pos = host.indexOf(':'); + + if (pos >= 0) { + host = host.substring(0, pos); + } + } + else { + host = null; + } + + return host; + } + + public String getHost(PortletRequest portletRequest) { + return getHost(getHttpServletRequest(portletRequest)); + } + + public HttpServletRequest getHttpServletRequest( + PortletRequest portletRequest) { + + PortletRequestImpl portletRequestImpl = + PortletRequestImpl.getPortletRequestImpl(portletRequest); + + return portletRequestImpl.getHttpServletRequest(); + } + + public HttpServletResponse getHttpServletResponse( + PortletResponse portletResponse) { + + PortletResponseImpl portletResponseImpl = + PortletResponseImpl.getPortletResponseImpl(portletResponse); + + return portletResponseImpl.getHttpServletResponse(); + } + + public String getJournalArticleActualURL( + long groupId, String mainPath, String friendlyURL, + Map params, Map requestContext) + throws PortalException, SystemException { + + String articleUrlTitle = friendlyURL.substring( + JournalArticleConstants.CANONICAL_URL_SEPARATOR.length()); + + JournalArticle journalArticle = + JournalArticleLocalServiceUtil.getArticleByUrlTitle( + groupId, articleUrlTitle); + + Layout layout = LayoutLocalServiceUtil.getLayoutByUuidAndGroupId( + journalArticle.getLayoutUuid(), groupId); + + String layoutActualURL = getLayoutActualURL(layout, mainPath); + + InheritableMap actualParams = + new InheritableMap(); + + if (params != null) { + actualParams.setParentMap(params); + } + + UnicodeProperties typeSettingsProperties = + layout.getTypeSettingsProperties(); + + String defaultAssetPublisherPortletId = typeSettingsProperties.get( + LayoutTypePortletConstants.DEFAULT_ASSET_PUBLISHER_PORTLET_ID); + + String currentDefaultAssetPublisherPortletId = + defaultAssetPublisherPortletId; + + if (Validator.isNull(defaultAssetPublisherPortletId)) { + defaultAssetPublisherPortletId = + PortletKeys.ASSET_PUBLISHER + + LayoutTypePortletImpl.getFullInstanceSeparator(); + } + + HttpServletRequest request = + (HttpServletRequest)requestContext.get("request"); + + if (Validator.isNull(currentDefaultAssetPublisherPortletId)) { + String actualPortletAuthenticationToken = AuthTokenUtil.getToken( + request, layout.getPlid(), defaultAssetPublisherPortletId); + + actualParams.put( + "p_p_auth", new String[] {actualPortletAuthenticationToken}); + } + + actualParams.put( + "p_p_id", new String[] {defaultAssetPublisherPortletId}); + actualParams.put("p_p_lifecycle", new String[] {"0"}); + + if (Validator.isNull(currentDefaultAssetPublisherPortletId)) { + actualParams.put( + "p_p_state", new String[] {WindowState.MAXIMIZED.toString()}); + } + + actualParams.put("p_p_mode", new String[] {"view"}); + actualParams.put( + "p_j_a_id", new String[] {String.valueOf(journalArticle.getId())}); + + String namespace = getPortletNamespace(defaultAssetPublisherPortletId); + + actualParams.put( + namespace + "struts_action", + new String[] {"/asset_publisher/view_content"}); + actualParams.put( + namespace + "type", + new String[] {JournalArticleAssetRendererFactory.TYPE}); + actualParams.put( + namespace + "urlTitle", + new String[] {journalArticle.getUrlTitle()}); + + String queryString = HttpUtil.parameterMapToString(actualParams, false); + + if (layoutActualURL.contains(StringPool.QUESTION)) { + layoutActualURL = + layoutActualURL + StringPool.AMPERSAND + queryString; + } + else { + layoutActualURL = + layoutActualURL + StringPool.QUESTION + queryString; + } + + Locale locale = getLocale(request); + + addPageSubtitle(journalArticle.getTitle(locale), request); + addPageDescription(journalArticle.getDescription(locale), request); + + List assetTags = AssetTagLocalServiceUtil.getTags( + JournalArticle.class.getName(), journalArticle.getPrimaryKey()); + + if (!assetTags.isEmpty()) { + addPageKeywords( + ListUtil.toString(assetTags, AssetTag.NAME_ACCESSOR), request); + } + + return layoutActualURL; + } + + public String getJsSafePortletId(String portletId) { + return JS.getSafeName(portletId); + } + + public String getLayoutActualURL(Layout layout) { + return getLayoutActualURL(layout, getPathMain()); + } + + public String getLayoutActualURL(Layout layout, String mainPath) { + Map variables = new HashMap(); + + variables.put("liferay:groupId", String.valueOf(layout.getGroupId())); + variables.put("liferay:mainPath", mainPath); + variables.put("liferay:plid", String.valueOf(layout.getPlid())); + + if (layout instanceof VirtualLayout) { + variables.put( + "liferay:pvlsgid", String.valueOf(layout.getGroupId())); + } + else { + variables.put("liferay:pvlsgid", "0"); + } + + LayoutType layoutType = layout.getLayoutType(); + + UnicodeProperties typeSettingsProperties = + layoutType.getTypeSettingsProperties(); + + variables.putAll(typeSettingsProperties); + + LayoutSettings layoutSettings = LayoutSettings.getInstance(layout); + + return layoutSettings.getURL(variables); + } + + public String getLayoutActualURL( + long groupId, boolean privateLayout, String mainPath, + String friendlyURL) + throws PortalException, SystemException { + + return getLayoutActualURL( + groupId, privateLayout, mainPath, friendlyURL, null, null); + } + + public String getLayoutActualURL( + long groupId, boolean privateLayout, String mainPath, + String friendlyURL, Map params, + Map requestContext) + throws PortalException, SystemException { + + Layout layout = null; + String queryString = StringPool.BLANK; + + if (Validator.isNull(friendlyURL)) { + List layouts = LayoutLocalServiceUtil.getLayouts( + groupId, privateLayout, + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); + + if (!layouts.isEmpty()) { + layout = layouts.get(0); + } + else { + throw new NoSuchLayoutException( + "{groupId=" + groupId + ",privateLayout=" + privateLayout + + "} does not have any layouts"); + } + } + else { + Object[] friendlyURLMapper = getPortletFriendlyURLMapper( + groupId, privateLayout, friendlyURL, params, requestContext); + + layout = (Layout)friendlyURLMapper[0]; + queryString = (String)friendlyURLMapper[1]; + } + + String layoutActualURL = getLayoutActualURL(layout, mainPath); + + if (Validator.isNotNull(queryString)) { + layoutActualURL = layoutActualURL.concat(queryString); + } + else if (params.isEmpty()) { + LayoutType layoutType = layout.getLayoutType(); + + UnicodeProperties typeSettingsProperties = + layoutType.getTypeSettingsProperties(); + + queryString = typeSettingsProperties.getProperty("query-string"); + + if (Validator.isNotNull(queryString) && + layoutActualURL.contains(StringPool.QUESTION)) { + + layoutActualURL = layoutActualURL.concat( + StringPool.AMPERSAND).concat(queryString); + } + } + + return layoutActualURL; + } + + public String getLayoutEditPage(Layout layout) { + LayoutSettings layoutSettings = LayoutSettings.getInstance( + layout.getType()); + + return layoutSettings.getEditPage(); + } + + public String getLayoutEditPage(String type) { + LayoutSettings layoutSettings = LayoutSettings.getInstance(type); + + return layoutSettings.getEditPage(); + } + + public String getLayoutFriendlyURL(Layout layout, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + if (!isLayoutFriendliable(layout)) { + return null; + } + + String groupFriendlyURL = getGroupFriendlyURL( + layout.getGroup(), layout.isPrivateLayout(), themeDisplay); + + return groupFriendlyURL.concat(layout.getFriendlyURL()); + } + + public String getLayoutFriendlyURL( + Layout layout, ThemeDisplay themeDisplay, Locale locale) + throws PortalException, SystemException { + + String i18nLanguageId = themeDisplay.getI18nLanguageId(); + String i18nPath = themeDisplay.getI18nPath(); + + try { + String tempI18nLanguageId = null; + String tempI18nPath = null; + + if (((I18nFilter.getLanguageIds().contains(locale.toString())) && + ((PropsValues.LOCALE_PREPEND_FRIENDLY_URL_STYLE == 1) && + (!locale.equals(LocaleUtil.getDefault())))) || + (PropsValues.LOCALE_PREPEND_FRIENDLY_URL_STYLE == 2)) { + + tempI18nLanguageId = locale.toString(); + tempI18nPath = buildI18NPath(locale); + } + + themeDisplay.setI18nLanguageId(tempI18nLanguageId); + themeDisplay.setI18nPath(tempI18nPath); + + return getLayoutFriendlyURL(layout, themeDisplay); + } + finally { + themeDisplay.setI18nLanguageId(i18nLanguageId); + themeDisplay.setI18nPath(i18nPath); + } + } + + public String getLayoutFullURL(Layout layout, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getLayoutFullURL(layout, themeDisplay, true); + } + + public String getLayoutFullURL( + Layout layout, ThemeDisplay themeDisplay, boolean doAsUser) + throws PortalException, SystemException { + + String layoutURL = getLayoutURL(layout, themeDisplay, doAsUser); + String portalURL = getPortalURL(layout, themeDisplay); + + if (StringUtil.startsWith(layoutURL, portalURL)) { + return layoutURL; + } + else { + return portalURL + layoutURL; + } + } + + public String getLayoutFullURL(long groupId, String portletId) + throws PortalException, SystemException { + + return getLayoutFullURL(groupId, portletId, false); + } + + public String getLayoutFullURL( + long groupId, String portletId, boolean secure) + throws PortalException, SystemException { + + long plid = getPlidFromPortletId(groupId, portletId); + + if (plid == LayoutConstants.DEFAULT_PLID) { + return null; + } + + StringBundler sb = new StringBundler(4); + + Layout layout = LayoutLocalServiceUtil.getLayout(plid); + + Group group = GroupLocalServiceUtil.getGroup(groupId); + + if (group.isLayout()) { + long parentGroupId = group.getParentGroupId(); + + if (parentGroupId > 0) { + group = GroupLocalServiceUtil.getGroup(parentGroupId); + } + } + + String virtualHostname = null; + + LayoutSet layoutSet = layout.getLayoutSet(); + + if (Validator.isNotNull(layoutSet.getVirtualHostname())) { + virtualHostname = layoutSet.getVirtualHostname(); + } + else { + Company company = CompanyLocalServiceUtil.getCompany( + layout.getCompanyId()); + + virtualHostname = company.getVirtualHostname(); + } + + String portalURL = getPortalURL( + virtualHostname, getPortalPort(secure), secure); + + sb.append(portalURL); + + if (layout.isPrivateLayout()) { + if (group.isUser()) { + sb.append(getPathFriendlyURLPrivateUser()); + } + else { + sb.append(getPathFriendlyURLPrivateGroup()); + } + } + else { + sb.append(getPathFriendlyURLPublic()); + } + + sb.append(group.getFriendlyURL()); + sb.append(layout.getFriendlyURL()); + + return sb.toString(); + } + + public String getLayoutFullURL(ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getLayoutFullURL(themeDisplay.getLayout(), themeDisplay); + } + + public String getLayoutSetFriendlyURL( + LayoutSet layoutSet, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + String virtualHostname = layoutSet.getVirtualHostname(); + + if (Validator.isNull(virtualHostname) && + Validator.isNotNull(PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME) && + !layoutSet.isPrivateLayout()) { + + try { + Group group = GroupLocalServiceUtil.getGroup( + themeDisplay.getCompanyId(), + PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME); + + if (layoutSet.getGroupId() == group.getGroupId()) { + Company company = themeDisplay.getCompany(); + + virtualHostname = company.getVirtualHostname(); + } + } + catch (Exception e) { + _log.error(e, e); + } + } + + if (Validator.isNotNull(virtualHostname)) { + String portalURL = getPortalURL( + virtualHostname, themeDisplay.getServerPort(), + themeDisplay.isSecure()); + + // Use the layout set's virtual host setting only if the layout set + // is already used for the current request + + long curLayoutSetId = + themeDisplay.getLayout().getLayoutSet().getLayoutSetId(); + + if ((layoutSet.getLayoutSetId() != curLayoutSetId) || + (portalURL.startsWith(themeDisplay.getURLPortal()))) { + + String layoutSetFriendlyURL = StringPool.BLANK; + + if (themeDisplay.isI18n()) { + layoutSetFriendlyURL = themeDisplay.getI18nPath(); + } + + return portalURL + _pathContext + layoutSetFriendlyURL; + } + } + + Group group = GroupLocalServiceUtil.getGroup(layoutSet.getGroupId()); + + String friendlyURL = null; + + if (layoutSet.isPrivateLayout()) { + if (group.isUser()) { + friendlyURL = _PRIVATE_USER_SERVLET_MAPPING; + } + else { + friendlyURL = _PRIVATE_GROUP_SERVLET_MAPPING; + } + } + else { + friendlyURL = _PUBLIC_GROUP_SERVLET_MAPPING; + } + + if (themeDisplay.isI18n()) { + friendlyURL = themeDisplay.getI18nPath() + friendlyURL; + } + + return _pathContext + friendlyURL + group.getFriendlyURL(); + } + + public String getLayoutTarget(Layout layout) { + UnicodeProperties typeSettingsProps = + layout.getTypeSettingsProperties(); + + String target = typeSettingsProps.getProperty("target"); + + if (Validator.isNull(target)) { + target = StringPool.BLANK; + } + else { + target = "target=\"" + HtmlUtil.escapeAttribute(target) + "\""; + } + + return target; + } + + public String getLayoutURL(Layout layout, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getLayoutURL(layout, themeDisplay, true); + } + + public String getLayoutURL( + Layout layout, ThemeDisplay themeDisplay, boolean doAsUser) + throws PortalException, SystemException { + + if (layout == null) { + return themeDisplay.getPathMain() + PATH_PORTAL_LAYOUT; + } + + if (!layout.isTypeURL()) { + String layoutFriendlyURL = getLayoutFriendlyURL( + layout, themeDisplay); + + if (Validator.isNotNull(layoutFriendlyURL)) { + layoutFriendlyURL = addPreservedParameters( + themeDisplay, layout, layoutFriendlyURL, doAsUser); + + return layoutFriendlyURL; + } + } + + String layoutURL = getLayoutActualURL(layout); + + layoutURL = addPreservedParameters( + themeDisplay, layout, layoutURL, doAsUser); + + return layoutURL; + } + + public String getLayoutURL(ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getLayoutURL(themeDisplay.getLayout(), themeDisplay); + } + + public String getLayoutViewPage(Layout layout) { + LayoutSettings layoutSettings = LayoutSettings.getInstance( + layout.getType()); + + return layoutSettings.getViewPage(); + } + + public String getLayoutViewPage(String type) { + LayoutSettings layoutSettings = LayoutSettings.getInstance(type); + + return layoutSettings.getViewPage(); + } + + public LiferayPortletRequest getLiferayPortletRequest( + PortletRequest portletRequest) { + + PortletRequestImpl portletRequestImpl = + PortletRequestImpl.getPortletRequestImpl(portletRequest); + + return portletRequestImpl; + } + + public LiferayPortletResponse getLiferayPortletResponse( + PortletResponse portletResponse) { + + PortletResponseImpl portletResponseImpl = + PortletResponseImpl.getPortletResponseImpl(portletResponse); + + return portletResponseImpl; + } + + public Locale getLocale(HttpServletRequest request) { + ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( + WebKeys.THEME_DISPLAY); + + if (themeDisplay != null) { + return themeDisplay.getLocale(); + } + else { + HttpSession session = request.getSession(); + + return (Locale)session.getAttribute(Globals.LOCALE_KEY); + } + } + + public Locale getLocale(RenderRequest renderRequest) { + return getLocale(getHttpServletRequest(renderRequest)); + } + + public String getMailId(String mx, String popPortletPrefix, Object... ids) { + StringBundler sb = new StringBundler(ids.length * 2 + 7); + + sb.append(StringPool.LESS_THAN); + sb.append(popPortletPrefix); + + if (!popPortletPrefix.endsWith(StringPool.PERIOD)) { + sb.append(StringPool.PERIOD); + } + + for (int i = 0; i < ids.length; i++) { + Object id = ids[i]; + + if (i != 0) { + sb.append(StringPool.PERIOD); + } + + sb.append(id); + } + + sb.append(StringPool.AT); + + if (Validator.isNotNull(PropsValues.POP_SERVER_SUBDOMAIN)) { + sb.append(PropsValues.POP_SERVER_SUBDOMAIN); + sb.append(StringPool.PERIOD); + } + + sb.append(mx); + sb.append(StringPool.GREATER_THAN); + + return sb.toString(); + } + + public String getNetvibesURL(Portlet portlet, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getServletURL( + portlet, PropsValues.NETVIBES_SERVLET_MAPPING, themeDisplay); + } + + public String getNewPortletTitle( + String portletTitle, String oldScopeName, String newScopeName) { + + if (portletTitle.endsWith(" (" + oldScopeName + ")")) { + int pos = portletTitle.lastIndexOf(" (" + oldScopeName + ")"); + + portletTitle = portletTitle.substring(0, pos); + } + + if (Validator.isNull(newScopeName)) { + return portletTitle; + } + + StringBundler sb = new StringBundler(5); + + sb.append(portletTitle); + sb.append(StringPool.SPACE); + sb.append(StringPool.OPEN_PARENTHESIS); + sb.append(newScopeName); + sb.append(StringPool.CLOSE_PARENTHESIS); + + return sb.toString(); + } + + public HttpServletRequest getOriginalServletRequest( + HttpServletRequest request) { + + HttpServletRequest originalRequest = request; + + while (originalRequest.getClass().getName().startsWith( + "com.liferay.")) { + + // Get original request so that portlets inside portlets render + // properly + + originalRequest = (HttpServletRequest) + ((HttpServletRequestWrapper)originalRequest).getRequest(); + } + + return originalRequest; + } + + public String getOuterPortletId(HttpServletRequest request) { + String outerPortletId = (String)request.getAttribute( + WebKeys.OUTER_PORTLET_ID); + + if (outerPortletId == null) { + outerPortletId = request.getParameter("p_o_p_id"); + } + + return outerPortletId; + } + + public long getParentGroupId(long groupId) + throws PortalException, SystemException { + + if (groupId <= 0) { + return 0; + } + + Group group = GroupLocalServiceUtil.getGroup(groupId); + + long parentGroupId = groupId; + + if (group.isLayout()) { + parentGroupId = group.getParentGroupId(); + } + + return parentGroupId; + } + + public String getPathContext() { + return _pathContext; + } + + public String getPathFriendlyURLPrivateGroup() { + return _pathFriendlyURLPrivateGroup; + } + + public String getPathFriendlyURLPrivateUser() { + return _pathFriendlyURLPrivateUser; + } + + public String getPathFriendlyURLPublic() { + return _pathFriendlyURLPublic; + } + + public String getPathImage() { + return _pathImage; + } + + public String getPathMain() { + return _pathMain; + } + + public String getPathProxy() { + return _pathProxy; + } + + public long getPlidFromFriendlyURL(long companyId, String friendlyURL) { + if (Validator.isNull(friendlyURL)) { + return LayoutConstants.DEFAULT_PLID; + } + + String[] urlParts = friendlyURL.split("\\/", 4); + + if ((friendlyURL.charAt(0) != CharPool.SLASH) && + (urlParts.length != 4)) { + + return LayoutConstants.DEFAULT_PLID; + } + + boolean privateLayout = true; + + String urlPrefix = StringPool.SLASH + urlParts[1]; + + if (_PUBLIC_GROUP_SERVLET_MAPPING.equals(urlPrefix)) { + privateLayout = false; + } + else if (_PRIVATE_GROUP_SERVLET_MAPPING.equals(urlPrefix) || + _PRIVATE_USER_SERVLET_MAPPING.equals(urlPrefix)) { + + privateLayout = true; + } + else { + return LayoutConstants.DEFAULT_PLID; + } + + Group group = null; + + try { + group = GroupLocalServiceUtil.getFriendlyURLGroup( + companyId, StringPool.SLASH + urlParts[2]); + } + catch (Exception e) { + } + + if (group != null) { + Layout layout = null; + + try { + String layoutFriendlyURL = null; + + if (urlParts.length == 4) { + layoutFriendlyURL = StringPool.SLASH + urlParts[3]; + + layout = LayoutLocalServiceUtil.getFriendlyURLLayout( + group.getGroupId(), privateLayout, layoutFriendlyURL); + } + else { + List layouts = LayoutLocalServiceUtil.getLayouts( + group.getGroupId(), privateLayout, + LayoutConstants.DEFAULT_PARENT_LAYOUT_ID, true, 0, 1); + + if (!layouts.isEmpty()) { + layout = layouts.get(0); + } + else { + return LayoutConstants.DEFAULT_PLID; + } + } + + return layout.getPlid(); + } + catch (Exception e) { + } + } + + return LayoutConstants.DEFAULT_PLID; + } + + public long getPlidFromPortletId( + long groupId, boolean privateLayout, String portletId) + throws PortalException, SystemException { + + long plid = LayoutConstants.DEFAULT_PLID; + + StringBundler sb = new StringBundler(5); + + sb.append(groupId); + sb.append(StringPool.SPACE); + sb.append(privateLayout); + sb.append(StringPool.SPACE); + sb.append(portletId); + + String key = sb.toString(); + + Long plidObj = _plidToPortletIdMap.get(key); + + if (plidObj == null) { + plid = doGetPlidFromPortletId(groupId, privateLayout, portletId); + + if (plid != LayoutConstants.DEFAULT_PLID) { + _plidToPortletIdMap.put(key, plid); + } + } + else { + plid = plidObj.longValue(); + + boolean validPlid = false; + + try { + Layout layout = LayoutLocalServiceUtil.getLayout(plid); + + LayoutTypePortlet layoutTypePortlet = + (LayoutTypePortlet)layout.getLayoutType(); + + if (layoutTypePortlet.hasDefaultScopePortletId( + groupId, portletId)) { + + validPlid = true; + } + } + catch (Exception e) { + } + + if (!validPlid) { + _plidToPortletIdMap.remove(key); + + plid = doGetPlidFromPortletId( + groupId, privateLayout, portletId); + + if (plid != LayoutConstants.DEFAULT_PLID) { + _plidToPortletIdMap.put(key, plid); + } + } + } + + return plid; + } + + public long getPlidFromPortletId(long groupId, String portletId) + throws PortalException, SystemException { + + long plid = getPlidFromPortletId(groupId, false, portletId); + + if (plid == LayoutConstants.DEFAULT_PLID) { + plid = getPlidFromPortletId(groupId, true, portletId); + } + + if (plid == LayoutConstants.DEFAULT_PLID) { + if (_log.isDebugEnabled()) { + _log.debug( + "Portlet " + portletId + + " does not exist on a page in group " + groupId); + } + } + + return plid; + } + + public String getPortalLibDir() { + return PropsValues.LIFERAY_LIB_PORTAL_DIR; + } + + /** + * @deprecated {@link #getPortalPort(boolean)} + */ + public int getPortalPort() { + return _portalPort.get(); + } + + public int getPortalPort(boolean secure) { + if (secure) { + return _securePortalPort.get(); + } + else { + return _portalPort.get(); + } + } + + public Properties getPortalProperties() { + return PropsUtil.getProperties(); + } + + public String getPortalURL(HttpServletRequest request) { + return getPortalURL(request, isSecure(request)); + } + + public String getPortalURL(HttpServletRequest request, boolean secure) { + return getPortalURL( + request.getServerName(), request.getServerPort(), secure); + } + + public String getPortalURL(Layout layout, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + String serverName = themeDisplay.getServerName(); + + if (layout == null) { + layout = themeDisplay.getLayout(); + } + + if (layout != null) { + LayoutSet layoutSet = layout.getLayoutSet(); + + String virtualHostname = layoutSet.getVirtualHostname(); + + if (Validator.isNotNull(virtualHostname)) { + serverName = virtualHostname; + } + } + + return getPortalURL( + serverName, themeDisplay.getServerPort(), themeDisplay.isSecure()); + } + + public String getPortalURL(PortletRequest portletRequest) { + return getPortalURL(portletRequest, portletRequest.isSecure()); + } + + public String getPortalURL(PortletRequest portletRequest, boolean secure) { + return getPortalURL( + portletRequest.getServerName(), portletRequest.getServerPort(), + secure); + } + + public String getPortalURL( + String serverName, int serverPort, boolean secure) { + + StringBundler sb = new StringBundler(); + + if (secure || Http.HTTPS.equals(PropsValues.WEB_SERVER_PROTOCOL)) { + sb.append(Http.HTTPS_WITH_SLASH); + } + else { + sb.append(Http.HTTP_WITH_SLASH); + } + + if (Validator.isNull(PropsValues.WEB_SERVER_HOST)) { + sb.append(serverName); + } + else { + sb.append(PropsValues.WEB_SERVER_HOST); + } + + if (!secure) { + if (PropsValues.WEB_SERVER_HTTP_PORT == -1) { + if ((serverPort != Http.HTTP_PORT) && + (serverPort != Http.HTTPS_PORT)) { + + sb.append(StringPool.COLON); + sb.append(serverPort); + } + } + else { + if (PropsValues.WEB_SERVER_HTTP_PORT != Http.HTTP_PORT) { + sb.append(StringPool.COLON); + sb.append(PropsValues.WEB_SERVER_HTTP_PORT); + } + } + } + + if (secure) { + if (PropsValues.WEB_SERVER_HTTPS_PORT == -1) { + if ((serverPort != Http.HTTP_PORT) && + (serverPort != Http.HTTPS_PORT)) { + + sb.append(StringPool.COLON); + sb.append(serverPort); + } + } + else { + if (PropsValues.WEB_SERVER_HTTPS_PORT != Http.HTTPS_PORT) { + sb.append(StringPool.COLON); + sb.append(PropsValues.WEB_SERVER_HTTPS_PORT); + } + } + } + + return sb.toString(); + } + + public String getPortalURL(ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getPortalURL(null, themeDisplay); + } + + public String getPortalWebDir() { + return PropsValues.LIFERAY_WEB_PORTAL_DIR; + } + + public Set getPortletAddDefaultResourceCheckWhitelist() { + return _portletAddDefaultResourceCheckWhitelist; + } + + public Set getPortletAddDefaultResourceCheckWhitelistActions() { + return _portletAddDefaultResourceCheckWhitelistActions; + } + + /** + * @deprecated {@link #getPortletBreadcrumbs(HttpServletRequest)} + */ + public List getPortletBreadcrumbList( + HttpServletRequest request) { + + return getPortletBreadcrumbs(request); + } + + public List getPortletBreadcrumbs( + HttpServletRequest request) { + + return (List)request.getAttribute( + WebKeys.PORTLET_BREADCRUMBS); + } + + public String getPortletDescription( + Portlet portlet, ServletContext servletContext, Locale locale) { + + PortletConfig portletConfig = PortletConfigFactoryUtil.create( + portlet, servletContext); + + ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale); + + return resourceBundle.getString( + JavaConstants.JAVAX_PORTLET_DESCRIPTION); + } + + public String getPortletDescription(Portlet portlet, User user) { + return getPortletDescription(portlet.getPortletId(), user); + } + + public String getPortletDescription(String portletId, Locale locale) { + return LanguageUtil.get( + locale, + JavaConstants.JAVAX_PORTLET_DESCRIPTION.concat( + StringPool.PERIOD).concat(portletId)); + } + + public String getPortletDescription(String portletId, String languageId) { + Locale locale = LocaleUtil.fromLanguageId(languageId); + + return getPortletDescription(portletId, locale); + } + + public String getPortletDescription(String portletId, User user) { + return LanguageUtil.get( + user.getLocale(), + JavaConstants.JAVAX_PORTLET_DESCRIPTION.concat( + StringPool.PERIOD).concat(portletId)); + } + + public Object[] getPortletFriendlyURLMapper( + long groupId, boolean privateLayout, String url, + Map params, Map requestContext) + throws PortalException, SystemException { + + boolean foundFriendlyURLMapper = false; + + String friendlyURL = url; + String queryString = StringPool.BLANK; + + List portlets = + PortletLocalServiceUtil.getFriendlyURLMapperPortlets(); + + Iterator itr = portlets.iterator(); + + while (itr.hasNext()) { + Portlet portlet = itr.next(); + + FriendlyURLMapper friendlyURLMapper = + portlet.getFriendlyURLMapperInstance(); + + if (url.endsWith( + StringPool.SLASH + friendlyURLMapper.getMapping())) { + + url += StringPool.SLASH; + } + + int pos = -1; + + if (friendlyURLMapper.isCheckMappingWithPrefix()) { + pos = url.indexOf( + FRIENDLY_URL_SEPARATOR + friendlyURLMapper.getMapping() + + StringPool.SLASH); + } + else { + pos = url.indexOf( + StringPool.SLASH + friendlyURLMapper.getMapping() + + StringPool.SLASH); + } + + if (pos != -1) { + foundFriendlyURLMapper = true; + + friendlyURL = url.substring(0, pos); + + InheritableMap actualParams = + new InheritableMap(); + + if (params != null) { + actualParams.setParentMap(params); + } + + Map prpIdentifiers = + new HashMap(); + + Set publicRenderParameters = + portlet.getPublicRenderParameters(); + + for (PublicRenderParameter publicRenderParameter : + publicRenderParameters) { + + QName qName = publicRenderParameter.getQName(); + + String publicRenderParameterIdentifier = + qName.getLocalPart(); + String publicRenderParameterName = + PortletQNameUtil.getPublicRenderParameterName(qName); + + prpIdentifiers.put( + publicRenderParameterIdentifier, + publicRenderParameterName); + } + + FriendlyURLMapperThreadLocal.setPRPIdentifiers(prpIdentifiers); + + if (friendlyURLMapper.isCheckMappingWithPrefix()) { + friendlyURLMapper.populateParams( + url.substring(pos + 2), actualParams, requestContext); + } + else { + friendlyURLMapper.populateParams( + url.substring(pos), actualParams, requestContext); + } + + queryString = + StringPool.AMPERSAND + + HttpUtil.parameterMapToString(actualParams, false); + + break; + } + } + + if (!foundFriendlyURLMapper) { + int x = url.indexOf(FRIENDLY_URL_SEPARATOR); + + if (x != -1) { + int y = url.indexOf(CharPool.SLASH, x + 3); + + if (y == -1) { + y = url.length(); + } + + String ppid = url.substring(x + 3, y); + + if (Validator.isNotNull(ppid)) { + friendlyURL = url.substring(0, x); + + Map actualParams = null; + + if (params != null) { + actualParams = new HashMap(params); + } + else { + actualParams = new HashMap(); + } + + actualParams.put("p_p_id", new String[] {ppid}); + actualParams.put("p_p_lifecycle", new String[] {"0"}); + actualParams.put( + "p_p_state", + new String[] {WindowState.MAXIMIZED.toString()}); + actualParams.put( + "p_p_mode", new String[] {PortletMode.VIEW.toString()}); + + queryString = + StringPool.AMPERSAND + + HttpUtil.parameterMapToString(actualParams, false); + } + } + } + + friendlyURL = StringUtil.replace( + friendlyURL, StringPool.DOUBLE_SLASH, StringPool.SLASH); + + if (friendlyURL.endsWith(StringPool.SLASH)) { + friendlyURL = friendlyURL.substring(0, friendlyURL.length() - 1); + } + + Layout layout = LayoutLocalServiceUtil.getFriendlyURLLayout( + groupId, privateLayout, friendlyURL); + + return new Object[] {layout, queryString}; + } + + public String getPortletId(HttpServletRequest request) { + PortletConfigImpl portletConfigImpl = + (PortletConfigImpl)request.getAttribute( + JavaConstants.JAVAX_PORTLET_CONFIG); + + if (portletConfigImpl != null) { + return portletConfigImpl.getPortletId(); + } + else { + return null; + } + } + + public String getPortletId(PortletRequest portletRequest) { + PortletConfigImpl portletConfigImpl = + (PortletConfigImpl)portletRequest.getAttribute( + JavaConstants.JAVAX_PORTLET_CONFIG); + + if (portletConfigImpl != null) { + return portletConfigImpl.getPortletId(); + } + else { + return null; + } + } + + public String getPortletLongTitle(Portlet portlet, Locale locale) { + return getPortletLongTitle(portlet.getPortletId(), locale); + } + + public String getPortletLongTitle( + Portlet portlet, ServletContext servletContext, Locale locale) { + + PortletConfig portletConfig = PortletConfigFactoryUtil.create( + portlet, servletContext); + + ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale); + + try { + String portletLongTitle = resourceBundle.getString( + JavaConstants.JAVAX_PORTLET_LONG_TITLE); + + if (portletLongTitle.startsWith( + JavaConstants.JAVAX_PORTLET_LONG_TITLE)) { + + portletLongTitle = getPortletTitle( + portlet, servletContext, locale); + } + + return portletLongTitle; + } + catch (Exception e) { + return getPortletTitle(portlet, servletContext, locale); + } + } + + public String getPortletLongTitle(Portlet portlet, String languageId) { + return getPortletLongTitle(portlet.getPortletId(), languageId); + } + + public String getPortletLongTitle(Portlet portlet, User user) { + return getPortletLongTitle(portlet.getPortletId(), user); + } + + public String getPortletLongTitle(String portletId, Locale locale) { + String portletLongTitle = LanguageUtil.get( + locale, + JavaConstants.JAVAX_PORTLET_LONG_TITLE.concat( + StringPool.PERIOD).concat(portletId), + StringPool.BLANK); + + if (Validator.isNull(portletLongTitle)) { + portletLongTitle = getPortletTitle(portletId, locale); + } + + return portletLongTitle; + } + + public String getPortletLongTitle(String portletId, String languageId) { + Locale locale = LocaleUtil.fromLanguageId(languageId); + + return getPortletLongTitle(portletId, locale); + } + + public String getPortletLongTitle(String portletId, User user) { + return getPortletLongTitle(portletId, user.getLocale()); + } + + public String getPortletNamespace(String portletId) { + return StringPool.UNDERLINE.concat(portletId).concat( + StringPool.UNDERLINE); + } + + public String getPortletTitle(Portlet portlet, Locale locale) { + return getPortletTitle(portlet.getPortletId(), locale); + } + + public String getPortletTitle( + Portlet portlet, ServletContext servletContext, Locale locale) { + + PortletConfig portletConfig = PortletConfigFactoryUtil.create( + portlet, servletContext); + + ResourceBundle resourceBundle = portletConfig.getResourceBundle(locale); + + return resourceBundle.getString(JavaConstants.JAVAX_PORTLET_TITLE); + } + + public String getPortletTitle(Portlet portlet, String languageId) { + return getPortletTitle(portlet.getPortletId(), languageId); + } + + public String getPortletTitle(Portlet portlet, User user) { + return getPortletTitle(portlet.getPortletId(), user); + } + + public String getPortletTitle(RenderResponse renderResponse) { + PortletResponseImpl portletResponseImpl = + PortletResponseImpl.getPortletResponseImpl(renderResponse); + + return ((RenderResponseImpl)portletResponseImpl).getTitle(); + } + + public String getPortletTitle(String portletId, Locale locale) { + return LanguageUtil.get( + locale, + JavaConstants.JAVAX_PORTLET_TITLE.concat(StringPool.PERIOD).concat( + portletId)); + } + + public String getPortletTitle(String portletId, String languageId) { + Locale locale = LocaleUtil.fromLanguageId(languageId); + + return getPortletTitle(portletId, locale); + } + + public String getPortletTitle(String portletId, User user) { + return LanguageUtil.get( + user.getLocale(), + JavaConstants.JAVAX_PORTLET_TITLE.concat(StringPool.PERIOD).concat( + portletId)); + } + + public String getPortletXmlFileName() throws SystemException { + if (PrefsPropsUtil.getBoolean( + PropsKeys.AUTO_DEPLOY_CUSTOM_PORTLET_XML, + PropsValues.AUTO_DEPLOY_CUSTOM_PORTLET_XML)) { + + return PORTLET_XML_FILE_NAME_CUSTOM; + } + else { + return PORTLET_XML_FILE_NAME_STANDARD; + } + } + + public PortletPreferences getPreferences(HttpServletRequest request) { + RenderRequest renderRequest = (RenderRequest)request.getAttribute( + JavaConstants.JAVAX_PORTLET_REQUEST); + + PortletPreferences portletPreferences = null; + + if (renderRequest != null) { + PortletPreferencesWrapper portletPreferencesWrapper = + (PortletPreferencesWrapper)renderRequest.getPreferences(); + + portletPreferences = + portletPreferencesWrapper.getPortletPreferencesImpl(); + } + + return portletPreferences; + } + + public PreferencesValidator getPreferencesValidator(Portlet portlet) { + PortletBag portletBag = PortletBagPool.get(portlet.getRootPortletId()); + + return portletBag.getPreferencesValidatorInstance(); + } + + public String getRelativeHomeURL(HttpServletRequest request) + throws PortalException, SystemException { + + Company company = getCompany(request); + + String homeURL = company.getHomeURL(); + + if (Validator.isNull(homeURL)) { + homeURL = PropsValues.COMPANY_DEFAULT_HOME_URL; + } + + return homeURL; + } + + public long getScopeGroupId(HttpServletRequest request) + throws PortalException, SystemException { + + String portletId = getPortletId(request); + + return getScopeGroupId(request, portletId); + } + + public long getScopeGroupId(HttpServletRequest request, String portletId) + throws PortalException, SystemException { + + return getScopeGroupId(request, portletId, false); + } + + public long getScopeGroupId( + HttpServletRequest request, String portletId, + boolean checkStagingGroup) + throws PortalException, SystemException { + + Layout layout = (Layout)request.getAttribute(WebKeys.LAYOUT); + + long scopeGroupId = 0; + + if (layout != null) { + Group group = layout.getGroup(); + + if (group.isControlPanel()) { + long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId"); + + Group doAsGroup = GroupLocalServiceUtil.fetchGroup(doAsGroupId); + + if ((doAsGroupId <= 0) || (doAsGroup == null)) { + doAsGroupId = getDefaultScopeGroupId(group.getCompanyId()); + } + + if (doAsGroupId > 0) { + scopeGroupId = doAsGroupId; + } + + group = GroupLocalServiceUtil.fetchGroup(scopeGroupId); + + if ((group != null) && group.hasStagingGroup()) { + try { + Group stagingGroup = group.getStagingGroup(); + + scopeGroupId = stagingGroup.getGroupId(); + } + catch (Exception e) { + } + } + } + + if ((portletId != null) && + (group.isStaged() || group.isStagingGroup())) { + + Group liveGroup = group; + + if (group.isStagingGroup()) { + liveGroup = group.getLiveGroup(); + } + + if (liveGroup.isStaged() && + !liveGroup.isStagedPortlet(portletId)) { + + Layout liveGroupLayout = + LayoutLocalServiceUtil.fetchLayoutByUuidAndGroupId( + layout.getUuid(), liveGroup.getGroupId()); + + if ((liveGroupLayout != null) && + liveGroupLayout.hasScopeGroup()) { + + scopeGroupId = getScopeGroupId( + liveGroupLayout, portletId); + } + else if (checkStagingGroup && + !liveGroup.isStagedRemotely()) { + + Group stagingGroup = liveGroup.getStagingGroup(); + + scopeGroupId = stagingGroup.getGroupId(); + } + else { + scopeGroupId = liveGroup.getGroupId(); + } + } + } + } + + if (scopeGroupId <= 0) { + scopeGroupId = getScopeGroupId(layout, portletId); + } + + return scopeGroupId; + } + + public long getScopeGroupId(Layout layout) { + if (layout == null) { + return 0; + } + else { + return layout.getGroupId(); + } + } + + public long getScopeGroupId(Layout layout, String portletId) { + if (layout == null) { + return 0; + } + + if (Validator.isNull(portletId)) { + return layout.getGroupId(); + } + + boolean strict = PortletPreferencesThreadLocal.isStrict(); + + PortletPreferencesThreadLocal.setStrict(true); + + try { + PortletPreferences portletSetup = + PortletPreferencesFactoryUtil.getLayoutPortletSetup( + layout, portletId); + + String scopeType = GetterUtil.getString( + portletSetup.getValue("lfrScopeType", null)); + + if (Validator.isNull(scopeType)) { + return layout.getGroupId(); + } + + if (scopeType.equals("company")) { + Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( + layout.getCompanyId()); + + return companyGroup.getGroupId(); + } + else { + String scopeLayoutUuid = GetterUtil.getString( + portletSetup.getValue("lfrScopeLayoutUuid", null)); + + Layout scopeLayout = + LayoutLocalServiceUtil.getLayoutByUuidAndGroupId( + scopeLayoutUuid, layout.getGroupId()); + + Group scopeGroup = scopeLayout.getScopeGroup(); + + return scopeGroup.getGroupId(); + } + } + catch (Exception e) { + return layout.getGroupId(); + } + finally { + PortletPreferencesThreadLocal.setStrict(strict); + } + } + + public long getScopeGroupId(long plid) { + Layout layout = null; + + try { + layout = LayoutLocalServiceUtil.getLayout(plid); + } + catch (Exception e) { + } + + return getScopeGroupId(layout); + } + + public long getScopeGroupId(PortletRequest portletRequest) + throws PortalException, SystemException { + + return getScopeGroupId(getHttpServletRequest(portletRequest)); + } + + public User getSelectedUser(HttpServletRequest request) + throws PortalException, SystemException { + + return getSelectedUser(request, true); + } + + public User getSelectedUser( + HttpServletRequest request, boolean checkPermission) + throws PortalException, SystemException { + + long userId = ParamUtil.getLong(request, "p_u_i_d"); + + User user = null; + + try { + if (checkPermission) { + user = UserServiceUtil.getUserById(userId); + } + else { + user = UserLocalServiceUtil.getUserById(userId); + } + } + catch (NoSuchUserException nsue) { + } + + return user; + } + + public User getSelectedUser(PortletRequest portletRequest) + throws PortalException, SystemException { + + return getSelectedUser(portletRequest, true); + } + + public User getSelectedUser( + PortletRequest portletRequest, boolean checkPermission) + throws PortalException, SystemException { + + return getSelectedUser( + getHttpServletRequest(portletRequest), checkPermission); + } + + public ServletContext getServletContext( + Portlet portlet, ServletContext servletContext) { + + PortletConfig portletConfig = PortletConfigFactoryUtil.create( + portlet, servletContext); + + PortletContextImpl portletContextImpl = + (PortletContextImpl)portletConfig.getPortletContext(); + + return portletContextImpl.getServletContext(); + } + + public String getSiteLoginURL(ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + if (Validator.isNull(PropsValues.AUTH_LOGIN_SITE_URL)) { + return null; + } + + List layouts = themeDisplay.getUnfilteredLayouts(); + + if (layouts == null) { + return null; + } + + for (Layout layout : layouts) { + String friendlyURL = layout.getFriendlyURL(); + + if (friendlyURL.equals(PropsValues.AUTH_LOGIN_SITE_URL)) { + if (themeDisplay.getLayout() == null) { + break; + } + + String layoutSetFriendlyURL = getLayoutSetFriendlyURL( + layout.getLayoutSet(), themeDisplay); + + return layoutSetFriendlyURL + PropsValues.AUTH_LOGIN_SITE_URL; + } + } + + return null; + } + + public String getStaticResourceURL(HttpServletRequest request, String uri) { + return getStaticResourceURL(request, uri, null, 0); + } + + public String getStaticResourceURL( + HttpServletRequest request, String uri, long timestamp) { + + return getStaticResourceURL(request, uri, null, timestamp); + } + + public String getStaticResourceURL( + HttpServletRequest request, String uri, String queryString) { + + return getStaticResourceURL(request, uri, queryString, 0); + } + + public String getStaticResourceURL( + HttpServletRequest request, String uri, String queryString, + long timestamp) { + + if (uri.indexOf(CharPool.QUESTION) != -1) { + return uri; + } + + if (uri.startsWith(StringPool.DOUBLE_SLASH)) { + uri = uri.substring(1); + } + + ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( + WebKeys.THEME_DISPLAY); + + Theme theme = themeDisplay.getTheme(); + ColorScheme colorScheme = themeDisplay.getColorScheme(); + + Map parameterMap = null; + + if (Validator.isNotNull(queryString)) { + parameterMap = HttpUtil.getParameterMap(queryString); + } + + StringBundler sb = new StringBundler(); + + // URI + + sb.append(uri); + sb.append(StringPool.QUESTION); + + // Browser id + + if ((parameterMap == null) || + (!parameterMap.containsKey("browserId"))) { + + sb.append("&browserId="); + sb.append(BrowserSnifferUtil.getBrowserId(request)); + } + + // Theme and color scheme + + if ((uri.endsWith(".css") || uri.endsWith(".jsp")) && + ((parameterMap == null) || !parameterMap.containsKey("themeId"))) { + + sb.append("&themeId="); + sb.append(theme.getThemeId()); + } + + if (uri.endsWith(".jsp") && + ((parameterMap == null) || + !parameterMap.containsKey("colorSchemeId"))) { + + sb.append("&colorSchemeId="); + sb.append(colorScheme.getColorSchemeId()); + } + + // Minifier + + if ((parameterMap == null) || + (!parameterMap.containsKey("minifierType"))) { + + String minifierType = StringPool.BLANK; + + if (uri.endsWith(".css") || uri.endsWith("css.jsp") || + uri.matches(".*/css/.*\\.jsp")) { + + if (themeDisplay.isThemeCssFastLoad()) { + minifierType = "css"; + } + } + else if (themeDisplay.isThemeJsFastLoad()) { + minifierType = "js"; + } + + if (Validator.isNotNull(minifierType)) { + sb.append("&minifierType="); + sb.append(minifierType); + } + } + + // Query string + + if (Validator.isNotNull(queryString)) { + if (!queryString.startsWith(StringPool.AMPERSAND)) { + sb.append(StringPool.AMPERSAND); + } + + sb.append(queryString); + } + + // Language id + + sb.append("&languageId="); + sb.append(themeDisplay.getLanguageId()); + + // Build number + + sb.append("&b="); + sb.append(ReleaseInfo.getBuildNumber()); + + // Timestamp + + if ((parameterMap == null) || !parameterMap.containsKey("t")) { + if ((timestamp == 0) && uri.startsWith(StrutsUtil.TEXT_HTML_DIR)) { + ServletContext servletContext = + (ServletContext)request.getAttribute(WebKeys.CTX); + + timestamp = FileTimestampUtil.getTimestamp(servletContext, uri); + } + + if (timestamp == 0) { + timestamp = theme.getTimestamp(); + } + + sb.append("&t="); + sb.append(timestamp); + } + + String url = sb.toString(); + + url = StringUtil.replace(url, "?&", StringPool.QUESTION); + + return url; + } + + public String getStrutsAction(HttpServletRequest request) { + String strutsAction = ParamUtil.getString(request, "struts_action"); + + if (Validator.isNotNull(strutsAction)) { + + // This method should only return a Struts action if you're dealing + // with a regular HTTP servlet request, not a portlet HTTP servlet + // request. + + return StringPool.BLANK; + } + + return getPortletParam(request, "struts_action"); + } + + public String[] getSystemGroups() { + return _allSystemGroups; + } + + public String[] getSystemOrganizationRoles() { + return _allSystemOrganizationRoles; + } + + public String[] getSystemRoles() { + return _allSystemRoles; + } + + public String[] getSystemSiteRoles() { + return _allSystemSiteRoles; + } + + public UploadPortletRequest getUploadPortletRequest( + PortletRequest portletRequest) { + + PortletRequestImpl portletRequestImpl = + (PortletRequestImpl)portletRequest; + + DynamicServletRequest dynamicRequest = + (DynamicServletRequest)portletRequestImpl.getHttpServletRequest(); + + HttpServletRequestWrapper requestWrapper = + (HttpServletRequestWrapper)dynamicRequest.getRequest(); + + UploadServletRequest uploadServletRequest = getUploadServletRequest( + requestWrapper); + + return new UploadPortletRequestImpl( + uploadServletRequest, + getPortletNamespace(portletRequestImpl.getPortletName())); + } + + public UploadServletRequest getUploadServletRequest( + HttpServletRequest request) { + + HttpServletRequestWrapper requestWrapper = null; + + if (request instanceof HttpServletRequestWrapper) { + requestWrapper = (HttpServletRequestWrapper)request; + } + + UploadServletRequest uploadServletRequest = null; + + while (uploadServletRequest == null) { + + // Find the underlying UploadServletRequest wrapper. For example, + // WebSphere wraps all requests with ProtectedServletRequest. + + if (requestWrapper instanceof UploadServletRequest) { + uploadServletRequest = (UploadServletRequest)requestWrapper; + } + else { + HttpServletRequest parentRequest = + (HttpServletRequest)requestWrapper.getRequest(); + + if (!(parentRequest instanceof HttpServletRequestWrapper)) { + + // This block should never be reached unless this method is + // called from a hot deployable portlet. See LayoutAction. + + uploadServletRequest = new UploadServletRequestImpl( + parentRequest); + + break; + } + else { + requestWrapper = (HttpServletRequestWrapper)parentRequest; + } + } + } + + return uploadServletRequest; + } + + public Date getUptime() { + return _upTime; + } + + public String getURLWithSessionId(String url, String sessionId) { + if (!PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID) { + return url; + } + + if (Validator.isNull(url)) { + return url; + } + + // LEP-4787 + + int x = url.indexOf(CharPool.SEMICOLON); + + if (x != -1) { + return url; + } + + x = url.indexOf(CharPool.QUESTION); + + if (x != -1) { + StringBundler sb = new StringBundler(4); + + sb.append(url.substring(0, x)); + sb.append(_JSESSIONID); + sb.append(sessionId); + sb.append(url.substring(x)); + + return sb.toString(); + } + + // In IE6, http://www.abc.com;jsessionid=XYZ does not work, but + // http://www.abc.com/;jsessionid=XYZ does work. + + x = url.indexOf(StringPool.DOUBLE_SLASH); + + StringBundler sb = new StringBundler(4); + + sb.append(url); + + if (x != -1) { + int y = url.lastIndexOf(CharPool.SLASH); + + if (x + 1 == y) { + sb.append(StringPool.SLASH); + } + } + + sb.append(_JSESSIONID); + sb.append(sessionId); + + return sb.toString(); + } + + public User getUser(HttpServletRequest request) + throws PortalException, SystemException { + + User user = (User)request.getAttribute(WebKeys.USER); + + if (user != null) { + return user; + } + + long userId = getUserId(request); + + if (userId <= 0) { + + // Portlet WARs may have the correct remote user and not have the + // correct user id because the user id is saved in the session + // and may not be accessible by the portlet WAR's session. This + // behavior is inconsistent across different application servers. + + String remoteUser = request.getRemoteUser(); + + if (remoteUser == null) { + return null; + } + + userId = GetterUtil.getLong(remoteUser); + } + + user = UserLocalServiceUtil.getUserById(userId); + + request.setAttribute(WebKeys.USER, user); + + return user; + } + + public User getUser(PortletRequest portletRequest) + throws PortalException, SystemException { + + return getUser(getHttpServletRequest(portletRequest)); + } + + public String getUserEmailAddress(long userId) throws SystemException { + try { + User user = UserLocalServiceUtil.getUserById(userId); + + return user.getEmailAddress(); + } + catch (PortalException pe) { + return StringPool.BLANK; + } + } + + public long getUserId(HttpServletRequest request) { + Long userIdObj = (Long)request.getAttribute(WebKeys.USER_ID); + + if (userIdObj != null) { + return userIdObj.longValue(); + } + + String path = GetterUtil.getString(request.getPathInfo()); + String strutsAction = getStrutsAction(request); + String actionName = getPortletParam(request, "actionName"); + + boolean alwaysAllowDoAsUser = false; + + if (path.equals("/portal/session_click") || + strutsAction.equals("/document_library/edit_file_entry") || + strutsAction.equals("/document_library_display/edit_file_entry") || + strutsAction.equals("/image_gallery_display/edit_file_entry") || + strutsAction.equals("/image_gallery_display/edit_image") || + strutsAction.equals("/wiki/edit_page_attachment") || + strutsAction.equals("/wiki_admin/edit_page_attachment") || + actionName.equals("addFile")) { + + try { + alwaysAllowDoAsUser = isAlwaysAllowDoAsUser(request); + } + catch (Exception e) { + _log.error(e, e); + } + } + + if ((!PropsValues.PORTAL_JAAS_ENABLE && + PropsValues.PORTAL_IMPERSONATION_ENABLE) || + (alwaysAllowDoAsUser)) { + + String doAsUserIdString = ParamUtil.getString( + request, "doAsUserId"); + + try { + long doAsUserId = getDoAsUserId( + request, doAsUserIdString, alwaysAllowDoAsUser); + + if (doAsUserId > 0) { + if (_log.isDebugEnabled()) { + _log.debug("Impersonating user " + doAsUserId); + } + + return doAsUserId; + } + } + catch (Exception e) { + _log.error("Unable to impersonate user " + doAsUserIdString, e); + } + } + + HttpSession session = request.getSession(); + + String jRemoteUser = null; + + if (PropsValues.PORTAL_JAAS_ENABLE) { + jRemoteUser = (String)session.getAttribute("j_remoteuser"); + } + + if (Validator.isNotNull(jRemoteUser)) { + userIdObj = GetterUtil.getLong(jRemoteUser); + } + else { + userIdObj = (Long)session.getAttribute(WebKeys.USER_ID); + } + + if (userIdObj != null) { + request.setAttribute(WebKeys.USER_ID, userIdObj); + + return userIdObj.longValue(); + } + else { + return 0; + } + } + + public long getUserId(PortletRequest portletRequest) { + return getUserId(getHttpServletRequest(portletRequest)); + } + + public String getUserName(long userId, String defaultUserName) { + return getUserName( + userId, defaultUserName, UserAttributes.USER_NAME_FULL); + } + + public String getUserName( + long userId, String defaultUserName, HttpServletRequest request) { + + return getUserName( + userId, defaultUserName, UserAttributes.USER_NAME_FULL, request); + } + + public String getUserName( + long userId, String defaultUserName, String userAttribute) { + + return getUserName(userId, defaultUserName, userAttribute, null); + } + + public String getUserName( + long userId, String defaultUserName, String userAttribute, + HttpServletRequest request) { + + String userName = defaultUserName; + + try { + User user = UserLocalServiceUtil.getUserById(userId); + + if (userAttribute.equals(UserAttributes.USER_NAME_FULL)) { + userName = user.getFullName(); + } + else { + userName = user.getScreenName(); + } + + if (request != null) { + Layout layout = (Layout)request.getAttribute(WebKeys.LAYOUT); + + PortletURL portletURL = new PortletURLImpl( + request, PortletKeys.DIRECTORY, layout.getPlid(), + PortletRequest.RENDER_PHASE); + + portletURL.setWindowState(WindowState.MAXIMIZED); + portletURL.setPortletMode(PortletMode.VIEW); + + portletURL.setParameter( + "struts_action", "/directory/view_user"); + portletURL.setParameter( + "p_u_i_d", String.valueOf(user.getUserId())); + + userName = + "" + + HtmlUtil.escape(userName) + ""; + } + } + catch (Exception e) { + } + + return userName; + } + + public String getUserPassword(HttpServletRequest request) { + HttpSession session = request.getSession(); + + return getUserPassword(session); + } + + public String getUserPassword(HttpSession session) { + return (String)session.getAttribute(WebKeys.USER_PASSWORD); + } + + public String getUserPassword(PortletRequest portletRequest) { + return getUserPassword(getHttpServletRequest(portletRequest)); + } + + public String getUserValue(long userId, String param, String defaultValue) + throws SystemException { + + if (Validator.isNotNull(defaultValue)) { + return defaultValue; + } + else { + try { + User user = UserLocalServiceUtil.getUserById(userId); + + return BeanPropertiesUtil.getString(user, param, defaultValue); + } + catch (PortalException pe) { + return StringPool.BLANK; + } + } + } + + public long getValidUserId(long companyId, long userId) + throws PortalException, SystemException { + + try { + User user = UserLocalServiceUtil.getUser(userId); + + if (user.getCompanyId() == companyId) { + return user.getUserId(); + } + else { + return userId; + } + } + catch (NoSuchUserException nsue) { + return UserLocalServiceUtil.getDefaultUserId(companyId); + } + } + + public String getVirtualLayoutActualURL( + long groupId, boolean privateLayout, String mainPath, + String friendlyURL, Map params, + Map requestContext) + throws PortalException, SystemException { + + // Group friendly URL + + String groupFriendlyURL = null; + + int pos = friendlyURL.indexOf(CharPool.SLASH, 3); + + if (pos != -1) { + groupFriendlyURL = friendlyURL.substring(2, pos); + } + + if (Validator.isNull(groupFriendlyURL)) { + return mainPath; + } + + HttpServletRequest request = (HttpServletRequest)requestContext.get( + "request"); + + long companyId = PortalInstances.getCompanyId(request); + + Group group = GroupLocalServiceUtil.fetchFriendlyURLGroup( + companyId, groupFriendlyURL); + + if (group == null) { + return mainPath; + } + + // Layout friendly URL + + String layoutFriendlyURL = null; + + if ((pos != -1) && ((pos + 1) != friendlyURL.length())) { + layoutFriendlyURL = friendlyURL.substring( + pos, friendlyURL.length()); + } + + if (Validator.isNull(layoutFriendlyURL)) { + return mainPath; + } + + String actualURL = getActualURL( + group.getGroupId(), privateLayout, mainPath, layoutFriendlyURL, + params, requestContext); + + return HttpUtil.addParameter( + HttpUtil.removeParameter(actualURL, "p_v_l_s_g_id"), "p_v_l_s_g_id", + groupId); + } + + public String getWidgetURL(Portlet portlet, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getServletURL( + portlet, PropsValues.WIDGET_SERVLET_MAPPING, themeDisplay); + } + + public void initCustomSQL() { + _customSqlKeys = new String[] { + "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.GROUP$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.LAYOUT$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.ORGANIZATION$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.ROLE$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.USER$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTAL.MODEL.USERGROUP$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.BLOGS.MODEL.BLOGSENTRY$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.BOOKMARKS.MODEL." + + "BOOKMARKSENTRY$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.CALENDAR.MODEL.CALEVENT$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.DOCUMENTLIBRARY.MODEL." + + "DLFILEENTRY$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.MESSAGEBOARDS.MODEL." + + "MBMESSAGE$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.MESSAGEBOARDS.MODEL." + + "MBTHREAD$]", + "[$CLASS_NAME_ID_COM.LIFERAY.PORTLET.WIKI.MODEL.WIKIPAGE$]", + "[$RESOURCE_SCOPE_COMPANY$]", "[$RESOURCE_SCOPE_GROUP$]", + "[$RESOURCE_SCOPE_GROUP_TEMPLATE$]", + "[$RESOURCE_SCOPE_INDIVIDUAL$]", + "[$SOCIAL_RELATION_TYPE_BI_COWORKER$]", + "[$SOCIAL_RELATION_TYPE_BI_FRIEND$]", + "[$SOCIAL_RELATION_TYPE_BI_ROMANTIC_PARTNER$]", + "[$SOCIAL_RELATION_TYPE_BI_SIBLING$]", + "[$SOCIAL_RELATION_TYPE_BI_SPOUSE$]", + "[$SOCIAL_RELATION_TYPE_UNI_CHILD$]", + "[$SOCIAL_RELATION_TYPE_UNI_ENEMY$]", + "[$SOCIAL_RELATION_TYPE_UNI_FOLLOWER$]", + "[$SOCIAL_RELATION_TYPE_UNI_PARENT$]", + "[$SOCIAL_RELATION_TYPE_UNI_SUBORDINATE$]", + "[$SOCIAL_RELATION_TYPE_UNI_SUPERVISOR$]", "[$FALSE$]", "[$TRUE$]" + }; + + DB db = DBFactoryUtil.getDB(); + + Object[] customSqlValues = new Object[] { + getClassNameId(Group.class), getClassNameId(Layout.class), + getClassNameId(Organization.class), getClassNameId(Role.class), + getClassNameId(User.class), getClassNameId(UserGroup.class), + getClassNameId(BlogsEntry.class), + getClassNameId(BookmarksEntry.class), + getClassNameId(CalEvent.class), getClassNameId(DLFileEntry.class), + getClassNameId(MBMessage.class), getClassNameId(MBThread.class), + getClassNameId(WikiPage.class), ResourceConstants.SCOPE_COMPANY, + ResourceConstants.SCOPE_GROUP, + ResourceConstants.SCOPE_GROUP_TEMPLATE, + ResourceConstants.SCOPE_INDIVIDUAL, + SocialRelationConstants.TYPE_BI_COWORKER, + SocialRelationConstants.TYPE_BI_FRIEND, + SocialRelationConstants.TYPE_BI_ROMANTIC_PARTNER, + SocialRelationConstants.TYPE_BI_SIBLING, + SocialRelationConstants.TYPE_BI_SPOUSE, + SocialRelationConstants.TYPE_UNI_CHILD, + SocialRelationConstants.TYPE_UNI_ENEMY, + SocialRelationConstants.TYPE_UNI_FOLLOWER, + SocialRelationConstants.TYPE_UNI_PARENT, + SocialRelationConstants.TYPE_UNI_SUBORDINATE, + SocialRelationConstants.TYPE_UNI_SUPERVISOR, db.getTemplateFalse(), + db.getTemplateTrue() + }; + + _customSqlValues = ArrayUtil.toStringArray(customSqlValues); + } + + public boolean isAllowAddPortletDefaultResource( + HttpServletRequest request, Portlet portlet) + throws PortalException, SystemException { + + ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( + WebKeys.THEME_DISPLAY); + + Layout layout = themeDisplay.getLayout(); + LayoutTypePortlet layoutTypePortlet = + themeDisplay.getLayoutTypePortlet(); + + String portletId = portlet.getPortletId(); + + Boolean renderPortletResource = (Boolean)request.getAttribute( + WebKeys.RENDER_PORTLET_RESOURCE); + + if (renderPortletResource != null) { + boolean runtimePortlet = renderPortletResource.booleanValue(); + + if (runtimePortlet) { + return true; + } + } + + if (layout.isTypePanel() && + isPanelSelectedPortlet(themeDisplay, portletId)) { + + return true; + } + + if (layout.isTypeControlPanel() && + isControlPanelPortlet(portletId, themeDisplay)) { + + return true; + } + + if (layout.isTypePortlet()) { + String checkPortletId = portletId; + + String outerPortletId = getOuterPortletId(request); + + if (outerPortletId != null) { + checkPortletId = outerPortletId; + } + + if (layoutTypePortlet.hasPortletId(checkPortletId)) { + return true; + } + } + + if (themeDisplay.isSignedIn() && + (portletId.equals(PortletKeys.LAYOUT_CONFIGURATION) || + portletId.equals(PortletKeys.LAYOUTS_ADMIN))) { + + PermissionChecker permissionChecker = + themeDisplay.getPermissionChecker(); + + Group group = layout.getGroup(); + + if (group.isSite()) { + if (LayoutPermissionUtil.contains( + permissionChecker, layout, ActionKeys.CUSTOMIZE) || + LayoutPermissionUtil.contains( + permissionChecker, layout, ActionKeys.UPDATE)) { + + return true; + } + } + + if (group.isCompany()) { + if (permissionChecker.isCompanyAdmin()) { + return true; + } + } + else if (group.isLayoutPrototype()) { + long layoutPrototypeId = group.getClassPK(); + + if (LayoutPrototypePermissionUtil.contains( + permissionChecker, layoutPrototypeId, + ActionKeys.UPDATE)) { + + return true; + } + } + else if (group.isLayoutSetPrototype()) { + long layoutSetPrototypeId = group.getClassPK(); + + if (LayoutSetPrototypePermissionUtil.contains( + permissionChecker, layoutSetPrototypeId, + ActionKeys.UPDATE)) { + + return true; + } + } + else if (group.isOrganization()) { + long organizationId = group.getOrganizationId(); + + if (OrganizationPermissionUtil.contains( + permissionChecker, organizationId, ActionKeys.UPDATE)) { + + return true; + } + } + else if (group.isUserGroup()) { + long scopeGroupId = themeDisplay.getScopeGroupId(); + + if (GroupPermissionUtil.contains( + permissionChecker, scopeGroupId, ActionKeys.UPDATE)) { + + return true; + } + } + else if (group.isUser()) { + return true; + } + } + + if (!portlet.isAddDefaultResource()) { + return false; + } + + if (!PropsValues.PORTLET_ADD_DEFAULT_RESOURCE_CHECK_ENABLED) { + return true; + } + + if (_portletAddDefaultResourceCheckWhitelist.contains(portletId)) { + return true; + } + + String strutsAction = ParamUtil.getString(request, "struts_action"); + + if (_portletAddDefaultResourceCheckWhitelistActions.contains( + strutsAction)) { + + return true; + } + + String requestPortletAuthenticationToken = ParamUtil.getString( + request, "p_p_auth"); + + if (Validator.isNull(requestPortletAuthenticationToken)) { + HttpServletRequest originalRequest = getOriginalServletRequest( + request); + + requestPortletAuthenticationToken = ParamUtil.getString( + originalRequest, "p_p_auth"); + } + + if (Validator.isNotNull(requestPortletAuthenticationToken)) { + String actualPortletAuthenticationToken = AuthTokenUtil.getToken( + request, layout.getPlid(), portletId); + + if (requestPortletAuthenticationToken.equals( + actualPortletAuthenticationToken)) { + + return true; + } + } + + return false; + } + + /** + * @deprecated As of 6.1, renamed to {@link #isGroupAdmin(User, long)} + */ + public boolean isCommunityAdmin(User user, long groupId) throws Exception { + return isGroupAdmin(user, groupId); + } + + /** + * @deprecated As of 6.1, renamed to {@link #isGroupOwner(User, long)} + */ + public boolean isCommunityOwner(User user, long groupId) throws Exception { + return isGroupOwner(user, groupId); + } + + public boolean isCompanyAdmin(User user) throws Exception { + PermissionChecker permissionChecker = + PermissionCheckerFactoryUtil.create(user, true); + + return permissionChecker.isCompanyAdmin(); + } + + public boolean isCompanyControlPanelPortlet( + String portletId, String category, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + PermissionChecker permissionChecker = + themeDisplay.getPermissionChecker(); + + if (permissionChecker.isCompanyAdmin()) { + return true; + } + + Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( + themeDisplay.getCompanyId()); + + themeDisplay.setScopeGroupId(companyGroup.getGroupId()); + + return isControlPanelPortlet(portletId, category, themeDisplay); + } + + public boolean isCompanyControlPanelPortlet( + String portletId, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + PermissionChecker permissionChecker = + themeDisplay.getPermissionChecker(); + + if (permissionChecker.isCompanyAdmin()) { + return true; + } + + Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( + themeDisplay.getCompanyId()); + + themeDisplay.setScopeGroupId(companyGroup.getGroupId()); + + return isControlPanelPortlet(portletId, themeDisplay); + } + + public boolean isCompanyControlPanelVisible(ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + PermissionChecker permissionChecker = + themeDisplay.getPermissionChecker(); + + if (permissionChecker.isCompanyAdmin()) { + return true; + } + + long scopeGroupId = themeDisplay.getScopeGroupId(); + + try { + Group companyGroup = GroupLocalServiceUtil.getCompanyGroup( + themeDisplay.getCompanyId()); + + themeDisplay.setScopeGroupId(companyGroup.getGroupId()); + + List controlPanelPortlets = getControlPanelPortlets( + PortletCategoryKeys.CONTENT, themeDisplay); + + if (!controlPanelPortlets.isEmpty()) { + return true; + } + else { + return false; + } + } + finally { + themeDisplay.setScopeGroupId(scopeGroupId); + } + } + + public boolean isControlPanelPortlet( + String portletId, String category, ThemeDisplay themeDisplay) + throws SystemException { + + List portlets = getControlPanelPortlets( + category, themeDisplay); + + for (Portlet portlet : portlets) { + if (portlet.getPortletId().equals(portletId)) { + return true; + } + } + + return false; + } + + public boolean isControlPanelPortlet( + String portletId, ThemeDisplay themeDisplay) + throws SystemException { + + for (String category : PortletCategoryKeys.ALL) { + if (isControlPanelPortlet(portletId, category, themeDisplay)) { + return true; + } + } + + return false; + } + + public boolean isGroupAdmin(User user, long groupId) throws Exception { + PermissionChecker permissionChecker = + PermissionCheckerFactoryUtil.create(user, true); + + return permissionChecker.isGroupAdmin(groupId); + } + + public boolean isGroupOwner(User user, long groupId) throws Exception { + PermissionChecker permissionChecker = + PermissionCheckerFactoryUtil.create(user, true); + + return permissionChecker.isGroupOwner(groupId); + } + + public boolean isLayoutDescendant(Layout layout, long layoutId) + throws PortalException, SystemException { + + if (layout.getLayoutId() == layoutId) { + return true; + } + else { + for (Layout childLayout : layout.getChildren()) { + if (isLayoutDescendant(childLayout, layoutId)) { + return true; + } + } + + return false; + } + } + + public boolean isLayoutFirstPageable(Layout layout) { + LayoutSettings layoutSettings = LayoutSettings.getInstance(layout); + + return layoutSettings.isFirstPageable(); + } + + public boolean isLayoutFirstPageable(String type) { + LayoutSettings layoutSettings = LayoutSettings.getInstance(type); + + return layoutSettings.isFirstPageable(); + } + + public boolean isLayoutFriendliable(Layout layout) { + LayoutSettings layoutSettings = LayoutSettings.getInstance(layout); + + return layoutSettings.isURLFriendliable(); + } + + public boolean isLayoutFriendliable(String type) { + LayoutSettings layoutSettings = LayoutSettings.getInstance(type); + + return layoutSettings.isURLFriendliable(); + } + + public boolean isLayoutParentable(Layout layout) { + return isLayoutParentable(layout.getType()); + } + + public boolean isLayoutParentable(String type) { + LayoutSettings layoutSettings = LayoutSettings.getInstance(type); + + return layoutSettings.isParentable(); + } + + public boolean isLayoutSitemapable(Layout layout) { + if (layout.isPrivateLayout()) { + return false; + } + + LayoutSettings layoutSettings = LayoutSettings.getInstance(layout); + + return layoutSettings.isSitemapable(); + } + + public boolean isMethodGet(PortletRequest portletRequest) { + HttpServletRequest request = getHttpServletRequest(portletRequest); + + String method = GetterUtil.getString(request.getMethod()); + + if (method.equalsIgnoreCase(HttpMethods.GET)) { + return true; + } + else { + return false; + } + } + + public boolean isMethodPost(PortletRequest portletRequest) { + HttpServletRequest request = getHttpServletRequest(portletRequest); + + String method = GetterUtil.getString(request.getMethod()); + + if (method.equalsIgnoreCase(HttpMethods.POST)) { + return true; + } + else { + return false; + } + } + + public boolean isMultipartRequest(HttpServletRequest request) { + String contentType = request.getHeader(HttpHeaders.CONTENT_TYPE); + + if ((contentType != null) && + contentType.startsWith(ContentTypes.MULTIPART_FORM_DATA)) { + + return true; + } + else { + return false; + } + } + + public boolean isOmniadmin(long userId) { + return OmniadminUtil.isOmniadmin(userId); + } + + public boolean isReservedParameter(String name) { + return _reservedParams.contains(name); + } + + public boolean isSecure(HttpServletRequest request) { + HttpSession session = request.getSession(); + + Boolean httpsInitial = (Boolean)session.getAttribute( + WebKeys.HTTPS_INITIAL); + + boolean secure = false; + + if ((PropsValues.COMPANY_SECURITY_AUTH_REQUIRES_HTTPS) && + (!PropsValues.SESSION_ENABLE_PHISHING_PROTECTION) && + (httpsInitial != null) && (!httpsInitial.booleanValue())) { + + secure = false; + } + else { + secure = request.isSecure(); + } + + return secure; + } + + public boolean isSystemGroup(String groupName) { + if (groupName == null) { + return false; + } + + groupName = groupName.trim(); + + int pos = Arrays.binarySearch( + _sortedSystemGroups, groupName, new StringComparator()); + + if (pos >= 0) { + return true; + } + else { + return false; + } + } + + public boolean isSystemRole(String roleName) { + if (roleName == null) { + return false; + } + + roleName = roleName.trim(); + + int pos = Arrays.binarySearch( + _sortedSystemRoles, roleName, new StringComparator()); + + if (pos >= 0) { + return true; + } + else { + pos = Arrays.binarySearch( + _sortedSystemSiteRoles, roleName, new StringComparator()); + + if (pos >= 0) { + return true; + } + else { + pos = Arrays.binarySearch( + _sortedSystemOrganizationRoles, roleName, + new StringComparator()); + + if (pos >= 0) { + return true; + } + } + } + + return false; + } + + public boolean isUpdateAvailable() throws SystemException { + return PluginPackageUtil.isUpdateAvailable(); + } + + public boolean isValidResourceId(String resourceId) { + if (Validator.isNull(resourceId)) { + return true; + } + + Matcher matcher = _bannedResourceIdPattern.matcher(resourceId); + + if (matcher.matches()) { + return false; + } + + return true; + } + + public void removePortalPortEventListener( + PortalPortEventListener portalPortEventListener) { + + _portalPortEventListeners.remove(portalPortEventListener); + } + + public String renderPage( + ServletContext servletContext, HttpServletRequest request, + HttpServletResponse response, String path) + throws IOException, ServletException { + + RequestDispatcher requestDispatcher = + servletContext.getRequestDispatcher(path); + + StringServletResponse stringResponse = new StringServletResponse( + response); + + requestDispatcher.include(request, stringResponse); + + return stringResponse.getString(); + } + + public String renderPortlet( + ServletContext servletContext, HttpServletRequest request, + HttpServletResponse response, Portlet portlet, String queryString, + boolean writeOutput) + throws IOException, ServletException { + + return renderPortlet( + servletContext, request, response, portlet, queryString, null, null, + null, writeOutput); + } + + public String renderPortlet( + ServletContext servletContext, HttpServletRequest request, + HttpServletResponse response, Portlet portlet, String queryString, + String columnId, Integer columnPos, Integer columnCount, + boolean writeOutput) + throws IOException, ServletException { + + return renderPortlet( + servletContext, request, response, portlet, queryString, columnId, + columnPos, columnCount, null, writeOutput); + } + + public String renderPortlet( + ServletContext servletContext, HttpServletRequest request, + HttpServletResponse response, Portlet portlet, String queryString, + String columnId, Integer columnPos, Integer columnCount, + String path, boolean writeOutput) + throws IOException, ServletException { + + queryString = GetterUtil.getString(queryString); + columnId = GetterUtil.getString(columnId); + + if (columnPos == null) { + columnPos = Integer.valueOf(0); + } + + if (columnCount == null) { + columnCount = Integer.valueOf(0); + } + + request.setAttribute(WebKeys.RENDER_PORTLET, portlet); + request.setAttribute(WebKeys.RENDER_PORTLET_QUERY_STRING, queryString); + request.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_ID, columnId); + request.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_POS, columnPos); + request.setAttribute(WebKeys.RENDER_PORTLET_COLUMN_COUNT, columnCount); + + if (path == null) { + path = "/html/portal/render_portlet.jsp"; + } + + RequestDispatcher requestDispatcher = + servletContext.getRequestDispatcher(path); + + UnsyncStringWriter unsyncStringWriter = new UnsyncStringWriter(); + + PipingServletResponse pipingServletResponse = new PipingServletResponse( + response, unsyncStringWriter); + + requestDispatcher.include(request, pipingServletResponse); + + boolean showPortlet = true; + + Boolean portletConfiguratorVisibility = (Boolean)request.getAttribute( + WebKeys.PORTLET_CONFIGURATOR_VISIBILITY); + + if (portletConfiguratorVisibility != null) { + ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( + WebKeys.THEME_DISPLAY); + + try { + Layout layout = themeDisplay.getLayout(); + + if (!layout.isTypeControlPanel() && + !LayoutPermissionUtil.contains( + themeDisplay.getPermissionChecker(), layout, + ActionKeys.UPDATE) && + !PortletPermissionUtil.contains( + themeDisplay.getPermissionChecker(), + themeDisplay.getPlid(), portlet.getPortletId(), + ActionKeys.CONFIGURATION)) { + + showPortlet = false; + } + } + catch (Exception e) { + throw new ServletException(e); + } + + request.removeAttribute(WebKeys.PORTLET_CONFIGURATOR_VISIBILITY); + } + + if (showPortlet) { + if (writeOutput) { + response.setContentType(ContentTypes.TEXT_HTML_UTF8); + + StringBundler sb = unsyncStringWriter.getStringBundler(); + + sb.writeTo(response.getWriter()); + + return StringPool.BLANK; + } + else { + return unsyncStringWriter.toString(); + } + } + else { + response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + + return StringPool.BLANK; + } + } + + public void resetCDNHosts() { + _cdnHostHttpMap.clear(); + _cdnHostHttpsMap.clear(); + + if (!ClusterInvokeThreadLocal.isEnabled()) { + return; + } + + ClusterRequest clusterRequest = ClusterRequest.createMulticastRequest( + _resetCDNHostsMethodHandler, true); + + try { + ClusterExecutorUtil.execute(clusterRequest); + } + catch (Exception e) { + _log.error("Unable to clear cluster wide CDN hosts", e); + } + } + + public Set resetPortletAddDefaultResourceCheckWhitelist() { + _portletAddDefaultResourceCheckWhitelist = SetUtil.fromArray( + PropsValues.PORTLET_ADD_DEFAULT_RESOURCE_CHECK_WHITELIST); + + _portletAddDefaultResourceCheckWhitelist = Collections.unmodifiableSet( + _portletAddDefaultResourceCheckWhitelist); + + return _portletAddDefaultResourceCheckWhitelist; + } + + public Set resetPortletAddDefaultResourceCheckWhitelistActions() { + _portletAddDefaultResourceCheckWhitelistActions = SetUtil.fromArray( + PropsValues.PORTLET_ADD_DEFAULT_RESOURCE_CHECK_WHITELIST_ACTIONS); + + _portletAddDefaultResourceCheckWhitelistActions = + Collections.unmodifiableSet( + _portletAddDefaultResourceCheckWhitelistActions); + + return _portletAddDefaultResourceCheckWhitelistActions; + } + + public void sendError( + Exception e, ActionRequest actionRequest, + ActionResponse actionResponse) + throws IOException { + + sendError(0, e, actionRequest, actionResponse); + } + + public void sendError( + Exception e, HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException { + + sendError(0, e, request, response); + } + + public void sendError( + int status, Exception e, ActionRequest actionRequest, + ActionResponse actionResponse) + throws IOException { + + StringBundler sb = new StringBundler(7); + + sb.append(_pathMain); + sb.append("/portal/status?status="); + sb.append(status); + sb.append("&exception="); + sb.append(e.getClass().getName()); + sb.append("&previousURL="); + sb.append(HttpUtil.encodeURL(getCurrentURL(actionRequest))); + + actionResponse.sendRedirect(sb.toString()); + } + + public void sendError( + int status, Exception e, HttpServletRequest request, + HttpServletResponse response) + throws IOException, ServletException { + + if (_log.isDebugEnabled()) { + String currentURL = (String)request.getAttribute( + WebKeys.CURRENT_URL); + + _log.debug( + "Current URL " + currentURL + " generates exception: " + + e.getMessage()); + } + + if (e instanceof NoSuchImageException) { + if (_logWebServerServlet.isWarnEnabled()) { + _logWebServerServlet.warn(e, e); + } + } + else if ((e instanceof PortalException) && _log.isDebugEnabled()) { + if ((e instanceof NoSuchLayoutException) || + (e instanceof PrincipalException)) { + + String msg = e.getMessage(); + + if (Validator.isNotNull(msg)) { + _log.debug(msg); + } + } + else { + _log.debug(e, e); + } + } + else if ((e instanceof SystemException) && _log.isWarnEnabled()) { + _log.warn(e, e); + } + + if (response.isCommitted()) { + return; + } + + if (status == 0) { + if (e instanceof PrincipalException) { + status = HttpServletResponse.SC_FORBIDDEN; + } + else { + String name = e.getClass().getName(); + + name = name.substring(name.lastIndexOf(CharPool.PERIOD) + 1); + + if (name.startsWith("NoSuch") && name.endsWith("Exception")) { + status = HttpServletResponse.SC_NOT_FOUND; + } + } + + if (status == 0) { + + // LPS-5352 + + if (PropsValues.TCK_URL) { + status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; + } + else { + status = HttpServletResponse.SC_BAD_REQUEST; + } + } + } + + HttpSession session = request.getSession(); + + ServletContext servletContext = session.getServletContext(); + + String redirect = PATH_MAIN + "/portal/status"; + + if ((e instanceof NoSuchLayoutException) && + Validator.isNotNull( + PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND)) { + + response.setStatus(status); + + redirect = PropsValues.LAYOUT_FRIENDLY_URL_PAGE_NOT_FOUND; + + RequestDispatcher requestDispatcher = + servletContext.getRequestDispatcher(redirect); + + if (requestDispatcher != null) { + requestDispatcher.forward(request, response); + } + } + else if (PropsValues.LAYOUT_SHOW_HTTP_STATUS) { + response.setStatus(status); + + SessionErrors.add(request, e.getClass().getName(), e); + + RequestDispatcher requestDispatcher = + servletContext.getRequestDispatcher(redirect); + + if (requestDispatcher != null) { + requestDispatcher.forward(request, response); + } + } + else { + if (e != null) { + response.sendError(status, e.getMessage()); + } + else { + response.sendError(status); + } + } + } + + public void setPageDescription( + String description, HttpServletRequest request) { + + request.setAttribute(WebKeys.PAGE_DESCRIPTION, description); + } + + public void setPageKeywords(String keywords, HttpServletRequest request) { + request.removeAttribute(WebKeys.PAGE_KEYWORDS); + + addPageKeywords(keywords, request); + } + + public void setPageSubtitle(String subtitle, HttpServletRequest request) { + request.setAttribute(WebKeys.PAGE_SUBTITLE, subtitle); + } + + public void setPageTitle(String title, HttpServletRequest request) { + request.setAttribute(WebKeys.PAGE_TITLE, title); + } + + public void setPortalPort(HttpServletRequest request) { + if (request.isSecure()) { + if (_securePortalPort.get() == -1) { + int securePortalPort = request.getServerPort(); + + _securePortalPort.compareAndSet(-1, securePortalPort); + } + } + else { + if (_portalPort.get() == -1) { + int portalPort = request.getServerPort(); + + if (_portalPort.compareAndSet(-1, portalPort)) { + notifyPortalPortEventListeners(portalPort); + } + } + } + } + + public void storePreferences(PortletPreferences portletPreferences) + throws IOException, ValidatorException { + + PortletPreferencesWrapper portletPreferencesWrapper = + (PortletPreferencesWrapper)portletPreferences; + + PortletPreferencesImpl portletPreferencesImpl = + portletPreferencesWrapper.getPortletPreferencesImpl(); + + portletPreferencesImpl.store(); + } + + public String[] stripURLAnchor(String url, String separator) { + String anchor = StringPool.BLANK; + + int pos = url.indexOf(separator); + + if (pos != -1) { + anchor = url.substring(pos); + url = url.substring(0, pos); + } + + return new String[] {url, anchor}; + } + + public String transformCustomSQL(String sql) { + if ((_customSqlKeys == null) || (_customSqlValues == null)) { + initCustomSQL(); + } + + return StringUtil.replace(sql, _customSqlKeys, _customSqlValues); + } + + public PortletMode updatePortletMode( + String portletId, User user, Layout layout, PortletMode portletMode, + HttpServletRequest request) { + + LayoutTypePortlet layoutType = + (LayoutTypePortlet)layout.getLayoutType(); + + if ((portletMode == null) || Validator.isNull(portletMode.toString())) { + if (layoutType.hasModeAboutPortletId(portletId)) { + return LiferayPortletMode.ABOUT; + } + else if (layoutType.hasModeConfigPortletId(portletId)) { + return LiferayPortletMode.CONFIG; + } + else if (layoutType.hasModeEditPortletId(portletId)) { + return PortletMode.EDIT; + } + else if (layoutType.hasModeEditDefaultsPortletId(portletId)) { + return LiferayPortletMode.EDIT_DEFAULTS; + } + else if (layoutType.hasModeEditGuestPortletId(portletId)) { + return LiferayPortletMode.EDIT_GUEST; + } + else if (layoutType.hasModeHelpPortletId(portletId)) { + return PortletMode.HELP; + } + else if (layoutType.hasModePreviewPortletId(portletId)) { + return LiferayPortletMode.PREVIEW; + } + else if (layoutType.hasModePrintPortletId(portletId)) { + return LiferayPortletMode.PRINT; + } + else { + return PortletMode.VIEW; + } + } + else { + boolean updateLayout = false; + + if (portletMode.equals(LiferayPortletMode.ABOUT) && + !layoutType.hasModeAboutPortletId(portletId)) { + + layoutType.addModeAboutPortletId(portletId); + + updateLayout = true; + } + else if (portletMode.equals(LiferayPortletMode.CONFIG) && + !layoutType.hasModeConfigPortletId(portletId)) { + + layoutType.addModeConfigPortletId(portletId); + + updateLayout = true; + } + else if (portletMode.equals(PortletMode.EDIT) && + !layoutType.hasModeEditPortletId(portletId)) { + + layoutType.addModeEditPortletId(portletId); + + updateLayout = true; + } + else if (portletMode.equals(LiferayPortletMode.EDIT_DEFAULTS) && + !layoutType.hasModeEditDefaultsPortletId(portletId)) { + + layoutType.addModeEditDefaultsPortletId(portletId); + + updateLayout = true; + } + else if (portletMode.equals(LiferayPortletMode.EDIT_GUEST) && + !layoutType.hasModeEditGuestPortletId(portletId)) { + + layoutType.addModeEditGuestPortletId(portletId); + + updateLayout = true; + } + else if (portletMode.equals(PortletMode.HELP) && + !layoutType.hasModeHelpPortletId(portletId)) { + + layoutType.addModeHelpPortletId(portletId); + + updateLayout = true; + } + else if (portletMode.equals(LiferayPortletMode.PREVIEW) && + !layoutType.hasModePreviewPortletId(portletId)) { + + layoutType.addModePreviewPortletId(portletId); + + updateLayout = true; + } + else if (portletMode.equals(LiferayPortletMode.PRINT) && + !layoutType.hasModePrintPortletId(portletId)) { + + layoutType.addModePrintPortletId(portletId); + + updateLayout = true; + } + else if (portletMode.equals(PortletMode.VIEW) && + !layoutType.hasModeViewPortletId(portletId)) { + + layoutType.removeModesPortletId(portletId); + + updateLayout = true; + } + + if (updateLayout) { + LayoutClone layoutClone = LayoutCloneFactory.getInstance(); + + if (layoutClone != null) { + layoutClone.update( + request, layout.getPlid(), layout.getTypeSettings()); + } + } + + return portletMode; + } + } + + public String updateRedirect( + String redirect, String oldPath, String newPath) { + + if (Validator.isNotNull(redirect) && (oldPath != null) && + !oldPath.equals(newPath)) { + + redirect = StringUtil.replace(redirect, oldPath, newPath); + redirect = StringUtil.replace( + redirect, HttpUtil.encodeURL(oldPath), + HttpUtil.encodeURL(newPath)); + } + + return redirect; + } + + public WindowState updateWindowState( + String portletId, User user, Layout layout, WindowState windowState, + HttpServletRequest request) { + + LayoutTypePortlet layoutType = + (LayoutTypePortlet)layout.getLayoutType(); + + if ((windowState == null) || + (Validator.isNull(windowState.toString()))) { + + if (layoutType.hasStateMaxPortletId(portletId)) { + windowState = WindowState.MAXIMIZED; + } + else if (layoutType.hasStateMinPortletId(portletId)) { + windowState = WindowState.MINIMIZED; + } + else { + windowState = WindowState.NORMAL; + } + } + else { + boolean updateLayout = false; + + if (windowState.equals(WindowState.MAXIMIZED) && + !layoutType.hasStateMaxPortletId(portletId)) { + + layoutType.addStateMaxPortletId(portletId); + + if (PropsValues.LAYOUT_REMEMBER_MAXIMIZED_WINDOW_STATE) { + updateLayout = true; + } + } + else if (windowState.equals(WindowState.MINIMIZED) && + !layoutType.hasStateMinPortletId(portletId)) { + + layoutType.addStateMinPortletId(portletId); + + updateLayout = true; + } + else if (windowState.equals(WindowState.NORMAL) && + !layoutType.hasStateNormalPortletId(portletId)) { + + layoutType.removeStatesPortletId(portletId); + + updateLayout = true; + } + + if (portletId.equals(PortletKeys.LAYOUTS_ADMIN) || + portletId.equals(PortletKeys.PORTLET_CONFIGURATION)) { + + updateLayout = false; + } + + if (updateLayout) { + LayoutClone layoutClone = LayoutCloneFactory.getInstance(); + + if (layoutClone != null) { + layoutClone.update( + request, layout.getPlid(), layout.getTypeSettings()); + } + } + } + + ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute( + WebKeys.THEME_DISPLAY); + + themeDisplay.setStateExclusive( + windowState.equals(LiferayWindowState.EXCLUSIVE)); + themeDisplay.setStateMaximized( + windowState.equals(WindowState.MAXIMIZED)); + themeDisplay.setStatePopUp( + windowState.equals(LiferayWindowState.POP_UP)); + + if (themeDisplay.isStateMaximized() && + themeDisplay.isShowAddContentIcon()) { + + themeDisplay.setShowAddContentIcon(false); + } + else if (!themeDisplay.isStateMaximized() && + !themeDisplay.isShowAddContentIcon() && + themeDisplay.isShowAddContentIconPermission()) { + + themeDisplay.setShowAddContentIcon(true); + } + + request.setAttribute(WebKeys.WINDOW_STATE, windowState); + + return windowState; + } + + protected void addDefaultResource( + long companyId, Layout layout, Portlet portlet, + boolean portletActions) + throws PortalException, SystemException { + + String rootPortletId = portlet.getRootPortletId(); + + String portletPrimaryKey = PortletPermissionUtil.getPrimaryKey( + layout.getPlid(), portlet.getPortletId()); + + String name = null; + String primaryKey = null; + + if (portletActions) { + name = rootPortletId; + primaryKey = portletPrimaryKey; + } + else { + name = ResourceActionsUtil.getPortletBaseResource(rootPortletId); + primaryKey = String.valueOf( + getScopeGroupId(layout, portlet.getPortletId())); + } + + if (Validator.isNull(name)) { + return; + } + + try { + if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { + int count = + ResourcePermissionLocalServiceUtil. + getResourcePermissionsCount( + companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, + primaryKey); + + if (count == 0) { + throw new NoSuchResourceException(); + } + } + else if (!portlet.isUndeployedPortlet()) { + ResourceLocalServiceUtil.getResource( + companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, + primaryKey); + } + } + catch (NoSuchResourceException nsre) { + ResourceLocalServiceUtil.addResources( + companyId, layout.getGroupId(), 0, name, primaryKey, + portletActions, true, true); + } + } + + protected void addDefaultResource( + ThemeDisplay themeDisplay, Layout layout, Portlet portlet, + boolean portletActions) + throws PortalException, SystemException { + + addDefaultResource( + themeDisplay.getCompanyId(), layout, portlet, portletActions); + } + + protected String buildI18NPath(Locale locale) { + String languageId = LocaleUtil.toLanguageId(locale); + + if (Validator.isNull(languageId)) { + return null; + } + + if (LanguageUtil.isDuplicateLanguageCode(locale.getLanguage())) { + Locale priorityLocale = LanguageUtil.getLocale( + locale.getLanguage()); + + if (locale.equals(priorityLocale)) { + languageId = locale.getLanguage(); + } + } + else { + languageId = locale.getLanguage(); + } + + return StringPool.SLASH.concat(languageId); + } + + protected long doGetPlidFromPortletId( + long groupId, boolean privateLayout, String portletId) + throws PortalException, SystemException { + + long scopeGroupId = groupId; + + try { + Group group = GroupLocalServiceUtil.getGroup(groupId); + + if (group.isLayout()) { + Layout scopeLayout = LayoutLocalServiceUtil.getLayout( + group.getClassPK()); + + groupId = scopeLayout.getGroupId(); + } + } + catch (Exception e) { + } + + long plid = LayoutConstants.DEFAULT_PLID; + + List layouts = LayoutLocalServiceUtil.getLayouts( + groupId, privateLayout, LayoutConstants.TYPE_PORTLET); + + for (Layout layout : layouts) { + LayoutTypePortlet layoutTypePortlet = + (LayoutTypePortlet)layout.getLayoutType(); + + if (layoutTypePortlet.hasPortletId(portletId)) { + if (getScopeGroupId(layout, portletId) == scopeGroupId) { + plid = layout.getPlid(); + + break; + } + } + } + + return plid; + } + + protected List filterControlPanelPortlets( + Set portlets, String category, ThemeDisplay themeDisplay) { + + Group group = themeDisplay.getScopeGroup(); + + List filteredPortlets = new ArrayList(); + + if (category.equals(PortletCategoryKeys.CONTENT) && group.isLayout()) { + for (Portlet portlet : portlets) { + if (portlet.isScopeable()) { + filteredPortlets.add(portlet); + } + } + } + else { + filteredPortlets.addAll(portlets); + } + + Iterator itr = filteredPortlets.iterator(); + + while (itr.hasNext()) { + Portlet portlet = itr.next(); + + try { + ControlPanelEntry controlPanelEntry = + portlet.getControlPanelEntryInstance(); + + if (controlPanelEntry == null) { + controlPanelEntry = + DefaultControlPanelEntryFactory.getInstance(); + } + + if (!controlPanelEntry.isVisible( + portlet, category, themeDisplay)) { + + itr.remove(); + } + } + catch (Exception e) { + _log.error(e, e); + + itr.remove(); + } + } + + return filteredPortlets; + } + + protected long getDefaultScopeGroupId(long companyId) + throws PortalException, SystemException { + + long doAsGroupId = 0; + + Collection portlets = getControlPanelPortlets( + companyId, PortletCategoryKeys.CONTENT); + + List groups = GroupServiceUtil.getManageableSites(portlets, 1); + + if (!groups.isEmpty()) { + Group group = groups.get(0); + + doAsGroupId = group.getGroupId(); + } + else { + Group guestGroup = GroupLocalServiceUtil.fetchGroup( + companyId, GroupConstants.GUEST); + + if (guestGroup != null) { + doAsGroupId = guestGroup.getGroupId(); + } + } + + return doAsGroupId; + } + + protected long getDoAsUserId( + HttpServletRequest request, String doAsUserIdString, + boolean alwaysAllowDoAsUser) + throws Exception { + + if (Validator.isNull(doAsUserIdString)) { + return 0; + } + + long doAsUserId = 0; + + try { + Company company = getCompany(request); + + doAsUserId = GetterUtil.getLong( + Encryptor.decrypt(company.getKeyObj(), doAsUserIdString)); + } + catch (Exception e) { + if (_log.isWarnEnabled()) { + _log.warn( + "Unable to impersonate " + doAsUserIdString + + " because the string cannot be decrypted", + e); + } + + return 0; + } + + if (_log.isDebugEnabled()) { + if (alwaysAllowDoAsUser) { + _log.debug( + "doAsUserId path or Struts action is always allowed"); + } + else { + _log.debug( + "doAsUserId path is Struts action not always allowed"); + } + } + + if (alwaysAllowDoAsUser) { + request.setAttribute(WebKeys.USER_ID, new Long(doAsUserId)); + + return doAsUserId; + } + + HttpSession session = request.getSession(); + + Long realUserIdObj = (Long)session.getAttribute(WebKeys.USER_ID); + + if (realUserIdObj == null) { + return 0; + } + + User doAsUser = UserLocalServiceUtil.getUserById(doAsUserId); + + long[] organizationIds = doAsUser.getOrganizationIds(); + + User realUser = UserLocalServiceUtil.getUserById( + realUserIdObj.longValue()); + boolean checkGuest = true; + + PermissionChecker permissionChecker = + PermissionCheckerFactoryUtil.create(realUser, checkGuest); + + if (doAsUser.isDefaultUser() || + UserPermissionUtil.contains( + permissionChecker, doAsUserId, organizationIds, + ActionKeys.IMPERSONATE)) { + + request.setAttribute(WebKeys.USER_ID, new Long(doAsUserId)); + + return doAsUserId; + } + else { + _log.error( + "User " + realUserIdObj + " does not have the permission " + + "to impersonate " + doAsUserId); + + return 0; + } + } + + protected String getGroupFriendlyURL( + Group group, boolean privateLayoutSet, ThemeDisplay themeDisplay, + boolean canonicalURL) + throws PortalException, SystemException { + + LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet( + group.getGroupId(), privateLayoutSet); + + String portalURL = StringPool.BLANK; + + if (canonicalURL || !themeDisplay.getServerName().equals(_LOCALHOST)) { + String virtualHostname = layoutSet.getVirtualHostname(); + + if (Validator.isNull(virtualHostname) && + Validator.isNotNull( + PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME) && + !layoutSet.isPrivateLayout()) { + + try { + Group defaultGroup = GroupLocalServiceUtil.getGroup( + themeDisplay.getCompanyId(), + PropsValues.VIRTUAL_HOSTS_DEFAULT_SITE_NAME); + + if (layoutSet.getGroupId() == defaultGroup.getGroupId()) { + Company company = themeDisplay.getCompany(); + + virtualHostname = company.getVirtualHostname(); + } + } + catch (Exception e) { + _log.error(e, e); + } + } + + if (Validator.isNotNull(virtualHostname) && + (canonicalURL || + !virtualHostname.equalsIgnoreCase(_LOCALHOST))) { + + virtualHostname = getPortalURL( + virtualHostname, themeDisplay.getServerPort(), + themeDisplay.isSecure()); + + String portalDomain = HttpUtil.getDomain( + themeDisplay.getPortalURL()); + + if (canonicalURL || virtualHostname.contains(portalDomain)) { + String path = StringPool.BLANK; + + if (themeDisplay.isWidget()) { + path = PropsValues.WIDGET_SERVLET_MAPPING; + } + + if (themeDisplay.isI18n() && !canonicalURL) { + path = themeDisplay.getI18nPath(); + } + + return virtualHostname.concat(_pathContext).concat(path); + } + } + else { + Layout curLayout = themeDisplay.getLayout(); + + LayoutSet curLayoutSet = curLayout.getLayoutSet(); + + if (canonicalURL || + ((layoutSet.getLayoutSetId() != + curLayoutSet.getLayoutSetId()) && + (group.getClassPK() != themeDisplay.getUserId()))) { + + if (group.isControlPanel()) { + virtualHostname = curLayoutSet.getVirtualHostname(); + } + + if (Validator.isNull(virtualHostname) || + virtualHostname.equalsIgnoreCase(_LOCALHOST)) { + + Company company = themeDisplay.getCompany(); + + virtualHostname = company.getVirtualHostname(); + } + + if (canonicalURL || + !virtualHostname.equalsIgnoreCase(_LOCALHOST)) { + + portalURL = getPortalURL( + virtualHostname, themeDisplay.getServerPort(), + themeDisplay.isSecure()); + } + } + } + } + + String friendlyURL = null; + + if (privateLayoutSet) { + if (group.isUser()) { + friendlyURL = _PRIVATE_USER_SERVLET_MAPPING; + } + else { + friendlyURL = _PRIVATE_GROUP_SERVLET_MAPPING; + } + } + else { + friendlyURL = _PUBLIC_GROUP_SERVLET_MAPPING; + } + + StringBundler sb = new StringBundler(6); + + sb.append(portalURL); + sb.append(_pathContext); + + if (themeDisplay.isI18n() && !canonicalURL) { + sb.append(themeDisplay.getI18nPath()); + } + + if (themeDisplay.isWidget()) { + sb.append(PropsValues.WIDGET_SERVLET_MAPPING); + } + + sb.append(friendlyURL); + sb.append(group.getFriendlyURL()); + + return sb.toString(); + } + + protected String getPortletParam(HttpServletRequest request, String name) { + String portletId = ParamUtil.getString(request, "p_p_id"); + + if (Validator.isNull(portletId)) { + return StringPool.BLANK; + } + + String value = null; + + int valueCount = 0; + + String keyName = StringPool.UNDERLINE.concat(name); + + Map parameterMap = request.getParameterMap(); + + for (Map.Entry entry : parameterMap.entrySet()) { + String parameterName = entry.getKey(); + + int pos = parameterName.indexOf(keyName); + + if (pos == -1) { + continue; + } + + valueCount++; + + // There should never be more than one value + + if (valueCount > 1) { + return StringPool.BLANK; + } + + String[] parameterValues = entry.getValue(); + + if ((parameterValues == null) || (parameterValues.length == 0) || + Validator.isNull(parameterValues[0])) { + + continue; + } + + // The Struts action must be for the correct portlet + + String portletId1 = parameterName.substring(1, pos); + + if (portletId.equals(portletId1)) { + value = parameterValues[0]; + } + } + + if (value == null) { + value = StringPool.BLANK; + } + + return value; + } + + protected String getServletURL( + Portlet portlet, String servletPath, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + Layout layout = themeDisplay.getLayout(); + + StringBundler sb = new StringBundler(); + + sb.append(themeDisplay.getPortalURL()); + + if (Validator.isNotNull(_pathContext)) { + sb.append(_pathContext); + } + + if (themeDisplay.isI18n()) { + sb.append(themeDisplay.getI18nPath()); + } + + sb.append(servletPath); + + Group group = layout.getGroup(); + + if (layout.isPrivateLayout()) { + if (group.isUser()) { + sb.append(_PRIVATE_USER_SERVLET_MAPPING); + } + else { + sb.append(_PRIVATE_GROUP_SERVLET_MAPPING); + } + } + else { + sb.append(_PUBLIC_GROUP_SERVLET_MAPPING); + } + + sb.append(group.getFriendlyURL()); + sb.append(layout.getFriendlyURL()); + + sb.append(FRIENDLY_URL_SEPARATOR); + + FriendlyURLMapper friendlyURLMapper = + portlet.getFriendlyURLMapperInstance(); + + if ((friendlyURLMapper != null) && !portlet.isInstanceable()) { + sb.append(friendlyURLMapper.getMapping()); + } + else { + sb.append(portlet.getPortletId()); + } + + return sb.toString(); + } + + protected boolean isAlwaysAllowDoAsUser(HttpServletRequest request) + throws Exception { + + String ticketKey = ParamUtil.getString(request, "ticketKey"); + + if (Validator.isNull(ticketKey)) { + return false; + } + + Ticket ticket = TicketLocalServiceUtil.fetchTicket(ticketKey); + + if (ticket == null) { + return false; + } + + String className = ticket.getClassName(); + + if (!className.equals(User.class.getName())) { + return false; + } + + long doAsUserId = 0; + + try { + Company company = getCompany(request); + + String doAsUserIdString = ParamUtil.getString( + request, "doAsUserId"); + + if (Validator.isNotNull(doAsUserIdString)) { + doAsUserId = GetterUtil.getLong( + Encryptor.decrypt(company.getKeyObj(), doAsUserIdString)); + } + } + catch (Exception e) { + return false; + } + + if ((ticket.getClassPK() != doAsUserId) || + (ticket.getType() != TicketConstants.TYPE_IMPERSONATE)) { + + return false; + } + + if (ticket.isExpired()) { + TicketLocalServiceUtil.deleteTicket(ticket); + + return false; + } + + Date expirationDate = new Date( + System.currentTimeMillis() + + PropsValues.SESSION_TIMEOUT * Time.MINUTE); + + ticket.setExpirationDate(expirationDate); + + TicketLocalServiceUtil.updateTicket(ticket, false); + + return true; + } + + protected boolean isPanelSelectedPortlet( + ThemeDisplay themeDisplay, String portletId) { + + Layout layout = themeDisplay.getLayout(); + + String panelSelectedPortlets = layout.getTypeSettingsProperty( + "panelSelectedPortlets"); + + if (Validator.isNotNull(panelSelectedPortlets)) { + String[] panelSelectedPortletsArray = StringUtil.split( + panelSelectedPortlets); + + return ArrayUtil.contains(panelSelectedPortletsArray, portletId); + } + + return false; + } + + protected void notifyPortalPortEventListeners(int portalPort) { + for (PortalPortEventListener portalPortEventListener : + _portalPortEventListeners) { + + portalPortEventListener.portalPortConfigured(portalPort); + } + } + + protected String removeRedirectParameter(String url) { + String queryString = HttpUtil.getQueryString(url); + + Map parameterMap = HttpUtil.getParameterMap( + queryString); + + for (String parameter : parameterMap.keySet()) { + if (parameter.endsWith("redirect")) { + url = HttpUtil.removeParameter(url, parameter); + } + } + + return url; + } + + private static final String _J_SECURITY_CHECK = "j_security_check"; + + private static final String _JSESSIONID = ";jsessionid="; + + private static final String _LOCALHOST = "localhost"; + + private static final String _PRIVATE_GROUP_SERVLET_MAPPING = + PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING; + + private static final String _PRIVATE_USER_SERVLET_MAPPING = + PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING; + + private static final String _PUBLIC_GROUP_SERVLET_MAPPING = + PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING; + + private static Log _log = LogFactoryUtil.getLog(PortalImpl.class); + + private static Log _logWebServerServlet = LogFactoryUtil.getLog( + WebServerServlet.class); + + private static Map _cdnHostHttpMap = + new ConcurrentHashMap(); + private static Map _cdnHostHttpsMap = + new ConcurrentHashMap(); + private static MethodHandler _resetCDNHostsMethodHandler = + new MethodHandler( + new MethodKey(PortalUtil.class.getName(), "resetCDNHosts")); + private static Date _upTime = new Date(); + + private String[] _allSystemGroups; + private String[] _allSystemOrganizationRoles; + private String[] _allSystemRoles; + private String[] _allSystemSiteRoles; + private Set _authTokenIgnoreActions; + private Set _authTokenIgnorePortlets; + private Pattern _bannedResourceIdPattern = Pattern.compile( + PropsValues.PORTLET_RESOURCE_ID_BANNED_PATHS_REGEXP, + Pattern.CASE_INSENSITIVE); + private String _computerAddress; + private String _computerName; + private String[] _customSqlKeys; + private String[] _customSqlValues; + private String _pathContext; + private String _pathFriendlyURLPrivateGroup; + private String _pathFriendlyURLPrivateUser; + private String _pathFriendlyURLPublic; + private String _pathImage; + private String _pathMain; + private String _pathProxy; + private Map _plidToPortletIdMap = + new ConcurrentHashMap(); + private final AtomicInteger _portalPort = new AtomicInteger(-1); + private List _portalPortEventListeners = + new ArrayList(); + private Set _portletAddDefaultResourceCheckWhitelist; + private Set _portletAddDefaultResourceCheckWhitelistActions; + private Set _reservedParams; + private final AtomicInteger _securePortalPort = new AtomicInteger(-1); + private String[] _sortedSystemGroups; + private String[] _sortedSystemOrganizationRoles; + private String[] _sortedSystemRoles; + private String[] _sortedSystemSiteRoles; + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portal/verify/VerifyJournal.java b/portal-impl/src/com/liferay/portal/verify/VerifyJournal.java index 6505c6df8634d1..ba8d36aeba6485 100644 --- a/portal-impl/src/com/liferay/portal/verify/VerifyJournal.java +++ b/portal-impl/src/com/liferay/portal/verify/VerifyJournal.java @@ -72,9 +72,8 @@ protected void doVerify() throws Exception { for (JournalTemplate template : templates) { ResourceLocalServiceUtil.addResources( - template.getCompanyId(), 0, 0, - JournalTemplate.class.getName(), template.getId(), false, false, - false); + template.getCompanyId(), 0, 0, JournalTemplate.class.getName(), + template.getId(), false, false, false); } if (_log.isDebugEnabled()) { diff --git a/portal-impl/src/com/liferay/portal/verify/VerifyProperties.java b/portal-impl/src/com/liferay/portal/verify/VerifyProperties.java index ea53c1a033faee..799c4f5f762a2d 100644 --- a/portal-impl/src/com/liferay/portal/verify/VerifyProperties.java +++ b/portal-impl/src/com/liferay/portal/verify/VerifyProperties.java @@ -187,47 +187,34 @@ protected void verifyRenamedSystemProperty(String oldKey, String newKey) }; private static final String[] _OBSOLETE_PORTAL_KEYS = new String[] { - "auth.max.failures.limit", - "cas.validate.url", - "commons.pool.enabled", - "jbi.workflow.url", - "lucene.analyzer", + "auth.max.failures.limit", "cas.validate.url", "commons.pool.enabled", + "jbi.workflow.url", "lucene.analyzer", "message.boards.thread.locking.enabled", - "portal.security.manager.enable", - "shard.available.names", - "webdav.storage.class", - "webdav.storage.show.edit.url", - "webdav.storage.show.view.url", - "webdav.storage.tokens", - "xss.allow" + "portal.security.manager.enable", "shard.available.names", + "webdav.storage.class", "webdav.storage.show.edit.url", + "webdav.storage.show.view.url", "webdav.storage.tokens", "xss.allow" }; private static final String[] _OBSOLETE_SYSTEM_KEYS = new String[] { - "com.liferay.util.Http.proxy.host", - "com.liferay.util.Http.proxy.port", + "com.liferay.util.Http.proxy.host", "com.liferay.util.Http.proxy.port", "com.liferay.util.XSSUtil.regexp.pattern" }; private static final String[][] _RENAMED_PORTAL_KEYS = new String[][] { new String[] { - "amazon.license.0", - "amazon.access.key.id" + "amazon.license.0", "amazon.access.key.id" }, new String[] { - "amazon.license.1", - "amazon.access.key.id" + "amazon.license.1", "amazon.access.key.id" }, new String[] { - "amazon.license.2", - "amazon.access.key.id" + "amazon.license.2", "amazon.access.key.id" }, new String[] { - "amazon.license.3", - "amazon.access.key.id" + "amazon.license.3", "amazon.access.key.id" }, new String[] { - "cdn.host", - "cdn.host.http" + "cdn.host", "cdn.host.http" }, new String[] { "com.liferay.portal.servlet.filters.compression.CompressionFilter", @@ -238,24 +225,20 @@ protected void verifyRenamedSystemProperty(String oldKey, String newKey) "default.guest.public.layout.friendly.url" }, new String[] { - "default.guest.layout.column", - "default.guest.public.layout.column" + "default.guest.layout.column", "default.guest.public.layout.column" }, new String[] { - "default.guest.layout.name", - "default.guest.public.layout.name" + "default.guest.layout.name", "default.guest.public.layout.name" }, new String[] { "default.guest.layout.template.id", "default.guest.public.layout.template.id" }, new String[] { - "default.user.layout.column", - "default.user.public.layout.column" + "default.user.layout.column", "default.user.public.layout.column" }, new String[] { - "default.user.layout.name", - "default.user.public.layout.name" + "default.user.layout.name", "default.user.public.layout.name" }, new String[] { "default.user.layout.template.id", @@ -266,8 +249,7 @@ protected void verifyRenamedSystemProperty(String oldKey, String newKey) "default.user.private.layouts.lar" }, new String[] { - "default.user.public.layout.lar", - "default.user.public.layouts.lar" + "default.user.public.layout.lar", "default.user.public.layouts.lar" }, new String[] { "dl.hook.cmis.credentials.password", @@ -278,44 +260,35 @@ protected void verifyRenamedSystemProperty(String oldKey, String newKey) "dl.store.cmis.credentials.username" }, new String[] { - "dl.hook.cmis.repository.url", - "dl.store.cmis.repository.url" + "dl.hook.cmis.repository.url", "dl.store.cmis.repository.url" }, new String[] { - "dl.hook.cmis.system.root.dir", - "dl.store.cmis.system.root.dir" + "dl.hook.cmis.system.root.dir", "dl.store.cmis.system.root.dir" }, new String[] { - "dl.hook.file.system.root.dir", - "dl.store.file.system.root.dir" + "dl.hook.file.system.root.dir", "dl.store.file.system.root.dir" }, new String[] { - "dl.hook.impl", - "dl.store.impl" + "dl.hook.impl", "dl.store.impl" }, new String[] { - "dl.hook.jcr.fetch.delay", - "dl.store.jcr.fetch.delay" + "dl.hook.jcr.fetch.delay", "dl.store.jcr.fetch.delay" }, new String[] { - "dl.hook.jcr.fetch.max.failures", - "dl.store.jcr.fetch.max.failures" + "dl.hook.jcr.fetch.max.failures", "dl.store.jcr.fetch.max.failures" }, new String[] { "dl.hook.jcr.move.version.labels", "dl.store.jcr.move.version.labels" }, new String[] { - "dl.hook.s3.access.key", - "dl.store.s3.access.key" + "dl.hook.s3.access.key", "dl.store.s3.access.key" }, new String[] { - "dl.hook.s3.bucket.name", - "dl.store.s3.bucket.name" + "dl.hook.s3.bucket.name", "dl.store.s3.bucket.name" }, new String[] { - "dl.hook.s3.secret.key", - "dl.store.s3.secret.key" + "dl.hook.s3.secret.key", "dl.store.s3.secret.key" }, new String[] { "editor.wysiwyg.portal-web.docroot.html.portlet.calendar." + @@ -352,16 +325,13 @@ protected void verifyRenamedSystemProperty(String oldKey, String newKey) "lucene.store.jdbc.auto.clean.up.enabled" }, new String[] { - "referer.url.domains.allowed", - "redirect.url.domains.allowed" + "referer.url.domains.allowed", "redirect.url.domains.allowed" }, new String[] { - "referer.url.ips.allowed", - "redirect.url.ips.allowed" + "referer.url.ips.allowed", "redirect.url.ips.allowed" }, new String[] { - "referer.url.security.mode", - "redirect.url.security.mode" + "referer.url.security.mode", "redirect.url.security.mode" }, new String[] { "tags.asset.increment.view.counter.enabled", diff --git a/portal-impl/src/com/liferay/portal/verify/VerifyResourcePermissions.java b/portal-impl/src/com/liferay/portal/verify/VerifyResourcePermissions.java index 903aadb31413bd..9be84a0a3b9aff 100644 --- a/portal-impl/src/com/liferay/portal/verify/VerifyResourcePermissions.java +++ b/portal-impl/src/com/liferay/portal/verify/VerifyResourcePermissions.java @@ -180,154 +180,96 @@ protected void verifyModel( private static final String[][] _MODELS = new String[][] { new String[] { - AnnouncementsEntry.class.getName(), - "AnnouncementsEntry", - "entryId" + AnnouncementsEntry.class.getName(), "AnnouncementsEntry", "entryId" }, new String[] { - AssetCategory.class.getName(), - "AssetCategory", - "categoryId" + AssetCategory.class.getName(), "AssetCategory", "categoryId" }, new String[] { - AssetTag.class.getName(), - "AssetTag", - "tagId" + AssetTag.class.getName(), "AssetTag", "tagId" }, new String[] { - AssetVocabulary.class.getName(), - "AssetVocabulary", - "vocabularyId" + AssetVocabulary.class.getName(), "AssetVocabulary", "vocabularyId" }, new String[] { - BlogsEntry.class.getName(), - "BlogsEntry", - "entryId" + BlogsEntry.class.getName(), "BlogsEntry", "entryId" }, new String[] { - BookmarksEntry.class.getName(), - "BookmarksEntry", - "entryId" + BookmarksEntry.class.getName(), "BookmarksEntry", "entryId" }, new String[] { - BookmarksFolder.class.getName(), - "BookmarksFolder", - "folderId" + BookmarksFolder.class.getName(), "BookmarksFolder", "folderId" }, new String[] { - CalEvent.class.getName(), - "CalEvent", - "eventId" + CalEvent.class.getName(), "CalEvent", "eventId" }, new String[] { - DDMStructure.class.getName(), - "DDMStructure", - "structureId" + DDMStructure.class.getName(), "DDMStructure", "structureId" }, new String[] { - DDMTemplate.class.getName(), - "DDMTemplate", - "templateId" + DDMTemplate.class.getName(), "DDMTemplate", "templateId" }, new String[] { - DLFileEntry.class.getName(), - "DLFileEntry", - "fileEntryId" + DLFileEntry.class.getName(), "DLFileEntry", "fileEntryId" }, new String[] { - DLFileShortcut.class.getName(), - "DLFileShortcut", - "fileShortcutId" + DLFileShortcut.class.getName(), "DLFileShortcut", "fileShortcutId" }, new String[] { - DLFolder.class.getName(), - "DLFolder", - "folderId" + DLFolder.class.getName(), "DLFolder", "folderId" }, new String[] { - JournalArticle.class.getName(), - "JournalArticle", - "resourcePrimKey" + JournalArticle.class.getName(), "JournalArticle", "resourcePrimKey" }, new String[] { - JournalFeed.class.getName(), - "JournalFeed", - "id_" + JournalFeed.class.getName(), "JournalFeed", "id_" }, new String[] { - JournalStructure.class.getName(), - "JournalStructure", - "id_" + JournalStructure.class.getName(), "JournalStructure", "id_" }, new String[] { - JournalTemplate.class.getName(), - "JournalTemplate", - "id_" + JournalTemplate.class.getName(), "JournalTemplate", "id_" }, new String[] { - LayoutSetBranch.class.getName(), - "LayoutSetBranch", + LayoutSetBranch.class.getName(), "LayoutSetBranch", "layoutSetBranchId" }, new String[] { - MBCategory.class.getName(), - "MBCategory", - "categoryId" + MBCategory.class.getName(), "MBCategory", "categoryId" }, new String[] { - MBMessage.class.getName(), - "MBMessage", - "messageId" + MBMessage.class.getName(), "MBMessage", "messageId" }, new String[] { - PasswordPolicy.class.getName(), - "PasswordPolicy", - "passwordPolicyId" + PasswordPolicy.class.getName(), "PasswordPolicy", "passwordPolicyId" }, new String[] { - PollsQuestion.class.getName(), - "PollsQuestion", - "questionId" + PollsQuestion.class.getName(), "PollsQuestion", "questionId" }, new String[] { - SCFrameworkVersion.class.getName(), - "SCFrameworkVersion", + SCFrameworkVersion.class.getName(), "SCFrameworkVersion", "frameworkVersionId" }, new String[] { - SCProductEntry.class.getName(), - "SCProductEntry", - "productEntryId" + SCProductEntry.class.getName(), "SCProductEntry", "productEntryId" }, new String[] { - ShoppingCategory.class.getName(), - "ShoppingCategory", - "categoryId" + ShoppingCategory.class.getName(), "ShoppingCategory", "categoryId" }, new String[] { - ShoppingItem.class.getName(), - "ShoppingItem", - "itemId" + ShoppingItem.class.getName(), "ShoppingItem", "itemId" }, new String[] { - Team.class.getName(), - "Team", - "teamId" + Team.class.getName(), "Team", "teamId" }, new String[] { - User.class.getName(), - "User_", - "userId" + User.class.getName(), "User_", "userId" }, new String[] { - WikiNode.class.getName(), - "WikiNode", - "nodeId" + WikiNode.class.getName(), "WikiNode", "nodeId" }, new String[] { - WikiPage.class.getName(), - "WikiPage", - "resourcePrimKey" + WikiPage.class.getName(), "WikiPage", "resourcePrimKey" } }; diff --git a/portal-impl/src/com/liferay/portal/verify/VerifyUUID.java b/portal-impl/src/com/liferay/portal/verify/VerifyUUID.java index 7bdfb928ad899b..f99a1b2a450490 100644 --- a/portal-impl/src/com/liferay/portal/verify/VerifyUUID.java +++ b/portal-impl/src/com/liferay/portal/verify/VerifyUUID.java @@ -77,40 +77,31 @@ protected void doVerify() throws Exception { private static final String[][] _MODELS = new String[][] { new String[] { - "DLFileVersion", - "fileVersionId" + "DLFileVersion", "fileVersionId" }, new String[] { - "JournalArticleResource", - "resourcePrimKey" + "JournalArticleResource", "resourcePrimKey" }, new String[] { - "JournalFeed", - "id_" + "JournalFeed", "id_" }, new String[] { - "JournalStructure", - "id_" + "JournalStructure", "id_" }, new String[] { - "JournalTemplate", - "id_" + "JournalTemplate", "id_" }, new String[] { - "Layout", - "plid" + "Layout", "plid" }, new String[] { - "LayoutPrototype", - "layoutPrototypeId" + "LayoutPrototype", "layoutPrototypeId" }, new String[] { - "LayoutSetPrototype", - "layoutSetPrototypeId" + "LayoutSetPrototype", "layoutSetPrototypeId" }, new String[] { - "WikiPageResource", - "resourcePrimKey" + "WikiPageResource", "resourcePrimKey" } }; diff --git a/portal-impl/src/com/liferay/portal/webdav/methods/BasePropMethodImpl.java b/portal-impl/src/com/liferay/portal/webdav/methods/BasePropMethodImpl.java index 4f23baa65a3b67..5462c4377929fd 100644 --- a/portal-impl/src/com/liferay/portal/webdav/methods/BasePropMethodImpl.java +++ b/portal-impl/src/com/liferay/portal/webdav/methods/BasePropMethodImpl.java @@ -418,15 +418,14 @@ protected int writeResponseXML( private static final List _ALL_COLLECTION_PROPS = Arrays.asList( new QName[] { - CREATIONDATE, DISPLAYNAME, GETLASTMODIFIED, - GETCONTENTTYPE, LOCKDISCOVERY, RESOURCETYPE + CREATIONDATE, DISPLAYNAME, GETLASTMODIFIED, GETCONTENTTYPE, + LOCKDISCOVERY, RESOURCETYPE }); private static final List _ALL_SIMPLE_PROPS = Arrays.asList( new QName[] { - CREATIONDATE, DISPLAYNAME, GETLASTMODIFIED, - GETCONTENTTYPE, GETCONTENTLENGTH, ISREADONLY, LOCKDISCOVERY, - RESOURCETYPE + CREATIONDATE, DISPLAYNAME, GETLASTMODIFIED, GETCONTENTTYPE, + GETCONTENTLENGTH, ISREADONLY, LOCKDISCOVERY, RESOURCETYPE }); private static Log _log = LogFactoryUtil.getLog(BasePropMethodImpl.class); diff --git a/portal-impl/src/com/liferay/portal/webserver/WebServerServlet.java b/portal-impl/src/com/liferay/portal/webserver/WebServerServlet.java index e39a78b3d52a05..88468b9240c0ba 100644 --- a/portal-impl/src/com/liferay/portal/webserver/WebServerServlet.java +++ b/portal-impl/src/com/liferay/portal/webserver/WebServerServlet.java @@ -788,8 +788,8 @@ protected void sendDocumentLibrary( } protected void sendFile( - HttpServletRequest request, HttpServletResponse response, - User user, String[] pathArray) + HttpServletRequest request, HttpServletResponse response, User user, + String[] pathArray) throws Exception { FileEntry fileEntry = getFileEntry(pathArray); diff --git a/portal-impl/src/com/liferay/portal/workflow/WorkflowLogManagerProxyBean.java b/portal-impl/src/com/liferay/portal/workflow/WorkflowLogManagerProxyBean.java index dbc8db121a108c..5dca0578cc66d5 100644 --- a/portal-impl/src/com/liferay/portal/workflow/WorkflowLogManagerProxyBean.java +++ b/portal-impl/src/com/liferay/portal/workflow/WorkflowLogManagerProxyBean.java @@ -49,8 +49,8 @@ public List getWorkflowLogsByWorkflowInstance( } public List getWorkflowLogsByWorkflowTask( - long companyId, long workflowTaskId, List logTypes, - int start, int end, OrderByComparator orderByComparator) { + long companyId, long workflowTaskId, List logTypes, int start, + int end, OrderByComparator orderByComparator) { throw new UnsupportedOperationException(); } diff --git a/portal-impl/src/com/liferay/portlet/PortletPreferencesFactoryImpl.java b/portal-impl/src/com/liferay/portlet/PortletPreferencesFactoryImpl.java index f03fffdc0e05dd..3bc4a41da1fc25 100644 --- a/portal-impl/src/com/liferay/portlet/PortletPreferencesFactoryImpl.java +++ b/portal-impl/src/com/liferay/portlet/PortletPreferencesFactoryImpl.java @@ -97,8 +97,7 @@ public PortletPreferencesImpl fromXML( populateMap(xml, preferencesMap); return new PortletPreferencesImpl( - companyId, ownerId, ownerType, plid, portletId, - preferencesMap); + companyId, ownerId, ownerType, plid, portletId, preferencesMap); } catch (SystemException se) { throw se; diff --git a/portal-impl/src/com/liferay/portlet/VelocityPortlet.java b/portal-impl/src/com/liferay/portlet/VelocityPortlet.java index 2d97f920606e26..fb76e4843bc7b3 100644 --- a/portal-impl/src/com/liferay/portlet/VelocityPortlet.java +++ b/portal-impl/src/com/liferay/portlet/VelocityPortlet.java @@ -212,8 +212,8 @@ protected void mergeTemplate( mergeTemplate( velocityTemplateId, - getVelocityContext(portletRequest, portletResponse), - portletRequest, portletResponse); + getVelocityContext(portletRequest, portletResponse), portletRequest, + portletResponse); } protected void mergeTemplate( diff --git a/portal-impl/src/com/liferay/portlet/amazonrankings/action/ConfigurationActionImpl.java b/portal-impl/src/com/liferay/portlet/amazonrankings/action/ConfigurationActionImpl.java index 7b5a3d60331de1..1670ac84ca026f 100644 --- a/portal-impl/src/com/liferay/portlet/amazonrankings/action/ConfigurationActionImpl.java +++ b/portal-impl/src/com/liferay/portlet/amazonrankings/action/ConfigurationActionImpl.java @@ -36,8 +36,7 @@ public void processAction( throws Exception { String[] isbns = StringUtil.split( - getParameter(actionRequest, "isbns").toUpperCase(), - CharPool.SPACE); + getParameter(actionRequest, "isbns").toUpperCase(), CharPool.SPACE); Arrays.sort(isbns); diff --git a/portal-impl/src/com/liferay/portlet/announcements/service/impl/AnnouncementsEntryServiceImpl.java b/portal-impl/src/com/liferay/portlet/announcements/service/impl/AnnouncementsEntryServiceImpl.java index ad20d61cc0a301..0b09f216141adf 100644 --- a/portal-impl/src/com/liferay/portlet/announcements/service/impl/AnnouncementsEntryServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/announcements/service/impl/AnnouncementsEntryServiceImpl.java @@ -115,12 +115,11 @@ public void deleteEntry(long entryId) } public AnnouncementsEntry updateEntry( - long entryId, String title, String content, String url, - String type, int displayDateMonth, int displayDateDay, - int displayDateYear, int displayDateHour, int displayDateMinute, - int expirationDateMonth, int expirationDateDay, - int expirationDateYear, int expirationDateHour, - int expirationDateMinute, int priority) + long entryId, String title, String content, String url, String type, + int displayDateMonth, int displayDateDay, int displayDateYear, + int displayDateHour, int displayDateMinute, int expirationDateMonth, + int expirationDateDay, int expirationDateYear, + int expirationDateHour, int expirationDateMinute, int priority) throws PortalException, SystemException { AnnouncementsEntryPermission.check( diff --git a/portal-impl/src/com/liferay/portlet/asset/service/persistence/AssetEntryFinderImpl.java b/portal-impl/src/com/liferay/portlet/asset/service/persistence/AssetEntryFinderImpl.java index 77d4e393693c6a..f20d485b787644 100644 --- a/portal-impl/src/com/liferay/portlet/asset/service/persistence/AssetEntryFinderImpl.java +++ b/portal-impl/src/com/liferay/portlet/asset/service/persistence/AssetEntryFinderImpl.java @@ -415,8 +415,7 @@ protected SQLQuery buildAssetQuerySQL( qPos.add(entryQuery.getNotAnyTagIds()); setDates( - qPos, entryQuery.getPublishDate(), - entryQuery.getExpirationDate()); + qPos, entryQuery.getPublishDate(), entryQuery.getExpirationDate()); qPos.add(entryQuery.getGroupIds()); qPos.add(entryQuery.getClassNameIds()); diff --git a/portal-impl/src/com/liferay/portlet/assetpublisher/action/ConfigurationActionImpl.java b/portal-impl/src/com/liferay/portlet/assetpublisher/action/ConfigurationActionImpl.java index 2af5441d732654..21b77c31f31b9c 100644 --- a/portal-impl/src/com/liferay/portlet/assetpublisher/action/ConfigurationActionImpl.java +++ b/portal-impl/src/com/liferay/portlet/assetpublisher/action/ConfigurationActionImpl.java @@ -327,8 +327,8 @@ protected void updateDefaultAssetPublisher(ActionRequest actionRequest) } layout = LayoutServiceUtil.updateLayout( - layout.getGroupId(), layout.isPrivateLayout(), - layout.getLayoutId(), layout.getTypeSettings()); + layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), + layout.getTypeSettings()); } protected void updateDisplaySettings(ActionRequest actionRequest) diff --git a/portal-impl/src/com/liferay/portlet/assetpublisher/util/AssetPublisherUtil.java b/portal-impl/src/com/liferay/portlet/assetpublisher/util/AssetPublisherUtil.java index 7bb453b8106858..4e28ebeb9e1237 100644 --- a/portal-impl/src/com/liferay/portlet/assetpublisher/util/AssetPublisherUtil.java +++ b/portal-impl/src/com/liferay/portlet/assetpublisher/util/AssetPublisherUtil.java @@ -466,8 +466,7 @@ public static long getRecentFolderId( } public static void removeAndStoreSelection( - List assetEntryUuids, - PortletPreferences portletPreferences) + List assetEntryUuids, PortletPreferences portletPreferences) throws Exception { if (assetEntryUuids.size() == 0) { diff --git a/portal-impl/src/com/liferay/portlet/blogs/atom/BlogsEntryAtomCollectionAdapter.java b/portal-impl/src/com/liferay/portlet/blogs/atom/BlogsEntryAtomCollectionAdapter.java index 2ac8eec72420ba..bd5375805effaf 100644 --- a/portal-impl/src/com/liferay/portlet/blogs/atom/BlogsEntryAtomCollectionAdapter.java +++ b/portal-impl/src/com/liferay/portlet/blogs/atom/BlogsEntryAtomCollectionAdapter.java @@ -186,9 +186,9 @@ protected BlogsEntry doPostEntry( return BlogsEntryServiceUtil.addEntry( title, summary, content, displayDateMonth, displayDateDay, - displayDateYear, displayDateHour, displayDateMinute, - allowPingbacks, allowTrackbacks, trackbacks, false, null, null, - null, serviceContext); + displayDateYear, displayDateHour, displayDateMinute, allowPingbacks, + allowTrackbacks, trackbacks, false, null, null, null, + serviceContext); } @Override diff --git a/portal-impl/src/com/liferay/portlet/blogs/lar/BlogsPortletDataHandlerImpl.java b/portal-impl/src/com/liferay/portlet/blogs/lar/BlogsPortletDataHandlerImpl.java index 309e1ae26c2199..165accd61dd74a 100644 --- a/portal-impl/src/com/liferay/portlet/blogs/lar/BlogsPortletDataHandlerImpl.java +++ b/portal-impl/src/com/liferay/portlet/blogs/lar/BlogsPortletDataHandlerImpl.java @@ -369,8 +369,7 @@ protected void importEntry( displayDateYear, displayDateHour, displayDateMinute, allowPingbacks, allowTrackbacks, trackbacks, entry.getSmallImage(), entry.getSmallImageURL(), - smallImageFileName, smallImageInputStream, - serviceContext); + smallImageFileName, smallImageInputStream, serviceContext); } portletDataContext.importClassedModel( diff --git a/portal-impl/src/com/liferay/portlet/blogs/lar/WordPressImporter.java b/portal-impl/src/com/liferay/portlet/blogs/lar/WordPressImporter.java index 0d8d5136005c93..0110cecbcba1f0 100644 --- a/portal-impl/src/com/liferay/portlet/blogs/lar/WordPressImporter.java +++ b/portal-impl/src/com/liferay/portlet/blogs/lar/WordPressImporter.java @@ -294,8 +294,8 @@ protected static void importEntry( entry = BlogsEntryLocalServiceUtil.addEntry( userId, title, StringPool.BLANK, content, displayDateMonth, displayDateDay, displayDateYear, displayDateHour, - displayDateMinute, allowPingbacks, allowTrackbacks, - null, false, null, null, null, serviceContext); + displayDateMinute, allowPingbacks, allowTrackbacks, null, false, + null, null, null, serviceContext); } catch (Exception e) { _log.error("Add entry " + title, e); diff --git a/portal-impl/src/com/liferay/portlet/blogs/service/persistence/BlogsEntryFinderImpl.java b/portal-impl/src/com/liferay/portlet/blogs/service/persistence/BlogsEntryFinderImpl.java index 75067cc2562c89..a576ed35c3f0a7 100644 --- a/portal-impl/src/com/liferay/portlet/blogs/service/persistence/BlogsEntryFinderImpl.java +++ b/portal-impl/src/com/liferay/portlet/blogs/service/persistence/BlogsEntryFinderImpl.java @@ -185,8 +185,8 @@ public List findByOrganizationId( } public List findByOrganizationIds( - List organizationIds, Date displayDate, int status, - int start, int end, OrderByComparator obc) + List organizationIds, Date displayDate, int status, int start, + int end, OrderByComparator obc) throws SystemException { Timestamp displayDate_TS = CalendarUtil.getTimestamp(displayDate); diff --git a/portal-impl/src/com/liferay/portlet/blogsadmin/search/EntrySearch.java b/portal-impl/src/com/liferay/portlet/blogsadmin/search/EntrySearch.java index 9b545143daed4b..c3ea20683261c5 100644 --- a/portal-impl/src/com/liferay/portlet/blogsadmin/search/EntrySearch.java +++ b/portal-impl/src/com/liferay/portlet/blogsadmin/search/EntrySearch.java @@ -50,8 +50,7 @@ portletRequest, new EntryDisplayTerms(portletRequest), iteratorURL.setParameter( EntryDisplayTerms.AUTHOR, displayTerms.getAuthor()); iteratorURL.setParameter( - EntryDisplayTerms.STATUS, - String.valueOf(displayTerms.getStatus())); + EntryDisplayTerms.STATUS, String.valueOf(displayTerms.getStatus())); iteratorURL.setParameter( EntryDisplayTerms.TITLE, displayTerms.getTitle()); } diff --git a/portal-impl/src/com/liferay/portlet/bookmarks/service/impl/BookmarksFolderLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/bookmarks/service/impl/BookmarksFolderLocalServiceImpl.java index 6fd5f4d3a674ea..c739cabfc34c13 100644 --- a/portal-impl/src/com/liferay/portlet/bookmarks/service/impl/BookmarksFolderLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/bookmarks/service/impl/BookmarksFolderLocalServiceImpl.java @@ -190,9 +190,8 @@ public void getSubfolderIds( } public BookmarksFolder updateFolder( - long folderId, long parentFolderId, String name, - String description, boolean mergeWithParentFolder, - ServiceContext serviceContext) + long folderId, long parentFolderId, String name, String description, + boolean mergeWithParentFolder, ServiceContext serviceContext) throws PortalException, SystemException { // Merge folders diff --git a/portal-impl/src/com/liferay/portlet/bookmarks/service/impl/BookmarksFolderServiceImpl.java b/portal-impl/src/com/liferay/portlet/bookmarks/service/impl/BookmarksFolderServiceImpl.java index 49d84818774219..688b36953dd0ea 100644 --- a/portal-impl/src/com/liferay/portlet/bookmarks/service/impl/BookmarksFolderServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/bookmarks/service/impl/BookmarksFolderServiceImpl.java @@ -110,9 +110,8 @@ public void getSubfolderIds( } public BookmarksFolder updateFolder( - long folderId, long parentFolderId, String name, - String description, boolean mergeWithParentFolder, - ServiceContext serviceContext) + long folderId, long parentFolderId, String name, String description, + boolean mergeWithParentFolder, ServiceContext serviceContext) throws PortalException, SystemException { BookmarksFolder folder = bookmarksFolderLocalService.getFolder( diff --git a/portal-impl/src/com/liferay/portlet/bookmarks/service/permission/BookmarksEntryPermission.java b/portal-impl/src/com/liferay/portlet/bookmarks/service/permission/BookmarksEntryPermission.java index 4e07de1332536b..1668740dabde7b 100644 --- a/portal-impl/src/com/liferay/portlet/bookmarks/service/permission/BookmarksEntryPermission.java +++ b/portal-impl/src/com/liferay/portlet/bookmarks/service/permission/BookmarksEntryPermission.java @@ -41,8 +41,7 @@ public static void check( } public static void check( - PermissionChecker permissionChecker, long entryId, - String actionId) + PermissionChecker permissionChecker, long entryId, String actionId) throws PortalException, SystemException { if (!contains(permissionChecker, entryId, actionId)) { @@ -84,8 +83,7 @@ public static boolean contains( } public static boolean contains( - PermissionChecker permissionChecker, long entryId, - String actionId) + PermissionChecker permissionChecker, long entryId, String actionId) throws PortalException, SystemException { BookmarksEntry entry = BookmarksEntryLocalServiceUtil.getEntry(entryId); diff --git a/portal-impl/src/com/liferay/portlet/bookmarks/util/BookmarksUtil.java b/portal-impl/src/com/liferay/portlet/bookmarks/util/BookmarksUtil.java index 08b0434a7ec3ca..fd83d4b4a38438 100644 --- a/portal-impl/src/com/liferay/portlet/bookmarks/util/BookmarksUtil.java +++ b/portal-impl/src/com/liferay/portlet/bookmarks/util/BookmarksUtil.java @@ -85,8 +85,7 @@ public static void addPortletBreadcrumbEntries( "struts_action", "/bookmarks/select_folder"); PortalUtil.addPortletBreadcrumbEntry( - request, themeDisplay.translate("home"), - portletURL.toString()); + request, themeDisplay.translate("home"), portletURL.toString()); } else { portletURL.setParameter("struts_action", "/bookmarks/view"); diff --git a/portal-impl/src/com/liferay/portlet/calendar/service/impl/CalEventLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/calendar/service/impl/CalEventLocalServiceImpl.java index 2055ff02bbd9a8..572634005211ad 100644 --- a/portal-impl/src/com/liferay/portlet/calendar/service/impl/CalEventLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/calendar/service/impl/CalEventLocalServiceImpl.java @@ -1221,51 +1221,33 @@ protected void remindUser(CalEvent event, User user, Calendar startDate) { subject = StringUtil.replace( subject, new String[] { - "[$EVENT_LOCATION$]", - "[$EVENT_START_DATE$]", - "[$EVENT_TITLE$]", - "[$FROM_ADDRESS$]", - "[$FROM_NAME$]", - "[$PORTAL_URL$]", - "[$PORTLET_NAME$]", - "[$TO_ADDRESS$]", + "[$EVENT_LOCATION$]", "[$EVENT_START_DATE$]", + "[$EVENT_TITLE$]", "[$FROM_ADDRESS$]", "[$FROM_NAME$]", + "[$PORTAL_URL$]", "[$PORTLET_NAME$]", "[$TO_ADDRESS$]", "[$TO_NAME$]" }, new String[] { event.getLocation(), dateFormatDateTime.format(startDate.getTime()), - event.getTitle(), - fromAddress, - fromName, - company.getPortalURL(event.getGroupId()), - portletName, - HtmlUtil.escape(toAddress), - HtmlUtil.escape(toName), + event.getTitle(), fromAddress, fromName, + company.getPortalURL(event.getGroupId()), portletName, + HtmlUtil.escape(toAddress), HtmlUtil.escape(toName), }); body = StringUtil.replace( body, new String[] { - "[$EVENT_LOCATION$]", - "[$EVENT_START_DATE$]", - "[$EVENT_TITLE$]", - "[$FROM_ADDRESS$]", - "[$FROM_NAME$]", - "[$PORTAL_URL$]", - "[$PORTLET_NAME$]", - "[$TO_ADDRESS$]", + "[$EVENT_LOCATION$]", "[$EVENT_START_DATE$]", + "[$EVENT_TITLE$]", "[$FROM_ADDRESS$]", "[$FROM_NAME$]", + "[$PORTAL_URL$]", "[$PORTLET_NAME$]", "[$TO_ADDRESS$]", "[$TO_NAME$]" }, new String[] { event.getLocation(), dateFormatDateTime.format(startDate.getTime()), - event.getTitle(), - fromAddress, - fromName, - company.getPortalURL(event.getGroupId()), - portletName, - HtmlUtil.escape(toAddress), - HtmlUtil.escape(toName), + event.getTitle(), fromAddress, fromName, + company.getPortalURL(event.getGroupId()), portletName, + HtmlUtil.escape(toAddress), HtmlUtil.escape(toName), }); if ((remindBy == CalEventConstants.REMIND_BY_EMAIL) || diff --git a/portal-impl/src/com/liferay/portlet/calendar/service/permission/CalEventPermission.java b/portal-impl/src/com/liferay/portlet/calendar/service/permission/CalEventPermission.java index 048a5f74ffa5dd..7d43036964832d 100644 --- a/portal-impl/src/com/liferay/portlet/calendar/service/permission/CalEventPermission.java +++ b/portal-impl/src/com/liferay/portlet/calendar/service/permission/CalEventPermission.java @@ -46,8 +46,7 @@ public static void check( } public static boolean contains( - PermissionChecker permissionChecker, CalEvent event, - String actionId) { + PermissionChecker permissionChecker, CalEvent event, String actionId) { if (permissionChecker.hasOwnerPermission( event.getCompanyId(), CalEvent.class.getName(), diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/action/EditFileEntryAction.java b/portal-impl/src/com/liferay/portlet/documentlibrary/action/EditFileEntryAction.java index 24af6318b45944..2bbfc82712571f 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/action/EditFileEntryAction.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/action/EditFileEntryAction.java @@ -308,8 +308,8 @@ protected void addMultipleFileEntries( for (String selectedFileName : selectedFileNames) { addMultipleFileEntries( - actionRequest, actionResponse, selectedFileName, - validFileNames, invalidFileNameKVPs); + actionRequest, actionResponse, selectedFileName, validFileNames, + invalidFileNameKVPs); } JSONArray jsonArray = JSONFactoryUtil.createJSONArray(); @@ -739,8 +739,8 @@ else if (cmd.equals(Constants.UPDATE_AND_CHECKIN)) { fileEntry = DLAppServiceUtil.updateFileEntryAndCheckIn( fileEntryId, sourceFileName, contentType, title, - description, changeLog, majorVersion, inputStream, - size, serviceContext); + description, changeLog, majorVersion, inputStream, size, + serviceContext); } else { @@ -748,8 +748,8 @@ else if (cmd.equals(Constants.UPDATE_AND_CHECKIN)) { fileEntry = DLAppServiceUtil.updateFileEntry( fileEntryId, sourceFileName, contentType, title, - description, changeLog, majorVersion, inputStream, - size, serviceContext); + description, changeLog, majorVersion, inputStream, size, + serviceContext); } AssetPublisherUtil.addRecentFolderId( diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/action/GetFileAction.java b/portal-impl/src/com/liferay/portlet/documentlibrary/action/GetFileAction.java index 57a79020dd66d8..4307c8664e917b 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/action/GetFileAction.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/action/GetFileAction.java @@ -142,9 +142,8 @@ public ActionForward strutsExecute( request, "groupId", themeDisplay.getScopeGroupId()); getFile( - fileEntryId, folderId, title, version, fileShortcutId, - uuid, groupId, targetExtension, themeDisplay, request, - response); + fileEntryId, folderId, title, version, fileShortcutId, uuid, + groupId, targetExtension, themeDisplay, request, response); return null; } diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/atom/FileEntryAtomCollectionAdapter.java b/portal-impl/src/com/liferay/portlet/documentlibrary/atom/FileEntryAtomCollectionAdapter.java index 1c34480595fab9..b98a14fea4029b 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/atom/FileEntryAtomCollectionAdapter.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/atom/FileEntryAtomCollectionAdapter.java @@ -249,8 +249,8 @@ protected FileEntry doPostMedia( @Override protected void doPutEntry( - FileEntry fileEntry, String title, String summary, - String content, Date date, AtomRequestContext atomRequestContext) + FileEntry fileEntry, String title, String summary, String content, + Date date, AtomRequestContext atomRequestContext) throws Exception { String mimeType = atomRequestContext.getHeader("Media-Content-Type"); diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/atom/FolderAtomCollectionAdapter.java b/portal-impl/src/com/liferay/portlet/documentlibrary/atom/FolderAtomCollectionAdapter.java index e3d05a4b3ca3dc..21bda803b77e83 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/atom/FolderAtomCollectionAdapter.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/atom/FolderAtomCollectionAdapter.java @@ -55,8 +55,7 @@ public AtomEntryContent getEntryContent( AtomEntryContent.Type.XML); String srcLink = AtomUtil.createCollectionLink( - atomRequestContext, - FileEntryAtomCollectionAdapter.COLLECTION_NAME); + atomRequestContext, FileEntryAtomCollectionAdapter.COLLECTION_NAME); srcLink += "?folderId=" + folder.getFolderId(); @@ -167,8 +166,8 @@ protected Folder doPostEntry( @Override protected void doPutEntry( - Folder folder, String title, String summary, - String content, Date date, AtomRequestContext atomRequestContext) + Folder folder, String title, String summary, String content, + Date date, AtomRequestContext atomRequestContext) throws Exception { ServiceContext serviceContext = new ServiceContext(); diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/lar/DLPortletDataHandlerImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/lar/DLPortletDataHandlerImpl.java index efb007ea69c7d4..7298e6e441669d 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/lar/DLPortletDataHandlerImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/lar/DLPortletDataHandlerImpl.java @@ -387,9 +387,9 @@ public static void importFileEntry( DLAppLocalServiceUtil.updateFileEntry( userId, existingFileEntry.getFileEntryId(), fileEntry.getTitle(), fileEntry.getMimeType(), - fileEntry.getTitle(), - fileEntry.getDescription(), null, false, is, - fileEntry.getSize(), serviceContext); + fileEntry.getTitle(), fileEntry.getDescription(), + null, false, is, fileEntry.getSize(), + serviceContext); } else { DLAppLocalServiceUtil.updateAsset( @@ -1091,8 +1091,8 @@ protected static void importFileEntryType( } else { DLFileEntryTypeLocalServiceUtil.updateFileEntryType( - userId, existingDLFileEntryType.getFileEntryTypeId(), - name, dlFileEntryType.getDescription(), ddmStrutureIds, + userId, existingDLFileEntryType.getFileEntryTypeId(), name, + dlFileEntryType.getDescription(), ddmStrutureIds, serviceContext); importedDLFileEntryType = existingDLFileEntryType; diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/search/EntriesChecker.java b/portal-impl/src/com/liferay/portlet/documentlibrary/search/EntriesChecker.java index ebcc5500122545..58f5f9cca06a03 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/search/EntriesChecker.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/search/EntriesChecker.java @@ -172,9 +172,7 @@ else if (folder != null) { checked, disabled, _liferayPortletResponse.getNamespace() + RowChecker.ROW_IDS + name + "Checkbox", - primaryKey, - checkBoxRowIds, - "'#" + getAllRowIds() + "Checkbox'", + primaryKey, checkBoxRowIds, "'#" + getAllRowIds() + "Checkbox'", _liferayPortletResponse.getNamespace() + "toggleActionsButton();"); } diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppHelperLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppHelperLocalServiceImpl.java index d5a36af3817228..554242a4b5e9aa 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppHelperLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppHelperLocalServiceImpl.java @@ -119,10 +119,10 @@ public void checkAssetEntry( if (fileEntryAssetEntry == null) { fileEntryAssetEntry = assetEntryLocalService.updateEntry( userId, fileEntry.getGroupId(), - DLFileEntryConstants.getClassName(), - fileEntry.getFileEntryId(), fileEntry.getUuid(), - fileEntryTypeId, assetCategoryIds, assetTagNames, false, null, - null, null, null, fileEntry.getMimeType(), fileEntry.getTitle(), + DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId(), + fileEntry.getUuid(), fileEntryTypeId, assetCategoryIds, + assetTagNames, false, null, null, null, null, + fileEntry.getMimeType(), fileEntry.getTitle(), fileEntry.getDescription(), null, null, null, 0, 0, null, false); } @@ -281,8 +281,8 @@ public void moveFolder(Folder folder) if (!isStagingGroup(folder.getGroupId())) { dlSyncLocalService.updateSync( - folder.getFolderId(), folder.getParentFolderId(), - folder.getName(), DLSyncConstants.EVENT_UPDATE, "-1"); + folder.getFolderId(), folder.getParentFolderId(), folder.getName(), + DLSyncConstants.EVENT_UPDATE, "-1"); } } @@ -355,10 +355,10 @@ public AssetEntry updateAsset( else { assetEntry = assetEntryLocalService.updateEntry( userId, fileEntry.getGroupId(), - DLFileEntryConstants.getClassName(), - fileEntry.getFileEntryId(), fileEntry.getUuid(), - fileEntryTypeId, assetCategoryIds, assetTagNames, visible, null, - null, null, null, fileEntry.getMimeType(), fileEntry.getTitle(), + DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId(), + fileEntry.getUuid(), fileEntryTypeId, assetCategoryIds, + assetTagNames, visible, null, null, null, null, + fileEntry.getMimeType(), fileEntry.getTitle(), fileEntry.getDescription(), null, null, null, 0, 0, null, false); @@ -371,11 +371,11 @@ public AssetEntry updateAsset( userId, dlFileShortcut.getGroupId(), DLFileShortcut.class.getName(), dlFileShortcut.getFileShortcutId(), - dlFileShortcut.getUuid(), fileEntryTypeId, - assetCategoryIds, assetTagNames, true, - null, null, null, null, fileEntry.getMimeType(), - fileEntry.getTitle(), fileEntry.getDescription(), null, - null, null, 0, 0, null, false); + dlFileShortcut.getUuid(), fileEntryTypeId, assetCategoryIds, + assetTagNames, true, null, null, null, null, + fileEntry.getMimeType(), fileEntry.getTitle(), + fileEntry.getDescription(), null, null, null, 0, 0, null, + false); } } @@ -480,8 +480,8 @@ public void updateStatus( 0, null, false); assetLinkLocalService.updateLinks( - userId, assetEntry.getEntryId(), - assetLinkEntryIds, AssetLinkConstants.TYPE_RELATED); + userId, assetEntry.getEntryId(), assetLinkEntryIds, + AssetLinkConstants.TYPE_RELATED); assetEntryLocalService.deleteEntry( draftAssetEntry.getEntryId()); @@ -528,8 +528,8 @@ else if (event.equals(DLSyncConstants.EVENT_UPDATE)) { } socialActivityLocalService.addUniqueActivity( - latestFileVersion.getStatusByUserId(), - fileEntry.getGroupId(), latestFileVersion.getCreateDate(), + latestFileVersion.getStatusByUserId(), fileEntry.getGroupId(), + latestFileVersion.getCreateDate(), DLFileEntryConstants.getClassName(), fileEntry.getFileEntryId(), activityType, StringPool.BLANK, 0); } diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppLocalServiceImpl.java index 4c133b8ae01fe9..3c494da74e0003 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppLocalServiceImpl.java @@ -538,8 +538,7 @@ public List getFileEntries( * @throws SystemException if a system exception occurred */ public List getFileEntriesAndFileShortcuts( - long repositoryId, long folderId, int status, int start, - int end) + long repositoryId, long folderId, int status, int start, int end) throws PortalException, SystemException { LocalRepository localRepository = getLocalRepository(repositoryId); diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppServiceImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppServiceImpl.java index a2348bbd2c82f6..f21ee32640bede 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLAppServiceImpl.java @@ -1479,8 +1479,8 @@ public List getGroupFileEntries( throws PortalException, SystemException { return getGroupFileEntries( - groupId, userId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, - start, end, new RepositoryModelModifiedDateComparator()); + groupId, userId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, start, + end, new RepositoryModelModifiedDateComparator()); } /** @@ -1517,8 +1517,8 @@ public List getGroupFileEntries( throws PortalException, SystemException { return getGroupFileEntries( - groupId, userId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, - start, end, obc); + groupId, userId, DLFolderConstants.DEFAULT_PARENT_FOLDER_ID, start, + end, obc); } /** @@ -2599,8 +2599,8 @@ public Void call() throws Exception { } protected void deleteFileEntry( - long oldFileEntryId, long newFileEntryId, - Repository fromRepository, Repository toRepository) + long oldFileEntryId, long newFileEntryId, Repository fromRepository, + Repository toRepository) throws PortalException, SystemException { try { diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFileEntryLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFileEntryLocalServiceImpl.java index b77441483475da..d77ca13e490e57 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFileEntryLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFileEntryLocalServiceImpl.java @@ -373,8 +373,8 @@ public DLFileEntry checkOutFileEntry( } lockLocalService.lock( - userId, DLFileEntry.class.getName(), fileEntryId, owner, - false, expirationTime); + userId, DLFileEntry.class.getName(), fileEntryId, owner, false, + expirationTime); } User user = userPersistence.findByPrimaryKey(userId); @@ -410,8 +410,7 @@ public DLFileEntry checkOutFileEntry( existingDLFileVersion.getFileEntryTypeId(), null, DLFileEntryConstants.PRIVATE_WORKING_COPY_VERSION, existingDLFileVersion.getSize(), - WorkflowConstants.STATUS_DRAFT, new Date(), - serviceContext); + WorkflowConstants.STATUS_DRAFT, new Date(), serviceContext); } else { dlFileVersion = addFileVersion( @@ -1501,10 +1500,9 @@ protected void startWorkflowInstance( workflowContext.put("event", syncEventType); WorkflowHandlerRegistryUtil.startWorkflowInstance( - dlFileVersion.getCompanyId(), dlFileVersion.getGroupId(), - userId, DLFileEntry.class.getName(), - dlFileVersion.getFileVersionId(), dlFileVersion, serviceContext, - workflowContext); + dlFileVersion.getCompanyId(), dlFileVersion.getGroupId(), userId, + DLFileEntry.class.getName(), dlFileVersion.getFileVersionId(), + dlFileVersion, serviceContext, workflowContext); } protected DLFileEntry updateFileEntry( @@ -1692,8 +1690,7 @@ protected DLFileVersion updateFileVersion( if ((fileEntryTypeId > 0) && (fieldsMap != null)) { dlFileEntryMetadataLocalService.updateFileEntryMetadata( fileEntryTypeId, dlFileVersion.getFileEntryId(), - dlFileVersion.getFileVersionId(), fieldsMap, - serviceContext); + dlFileVersion.getFileVersionId(), fieldsMap, serviceContext); } return dlFileVersion; diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFileEntryServiceImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFileEntryServiceImpl.java index 40dee861a09e32..6bbb7b789fb782 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFileEntryServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFileEntryServiceImpl.java @@ -61,8 +61,8 @@ public DLFileEntry addFileEntry( return dlFileEntryLocalService.addFileEntry( getUserId(), groupId, repositoryId, folderId, sourceFileName, - mimeType, title, description, changeLog, fileEntryTypeId, - fieldsMap, file, is, size, serviceContext); + mimeType, title, description, changeLog, fileEntryTypeId, fieldsMap, + file, is, size, serviceContext); } public void cancelCheckOut(long fileEntryId) @@ -257,8 +257,8 @@ public List getFileEntries( } public List getFileEntries( - long groupId, long folderId, String[] mimeTypes, int start, - int end, OrderByComparator obc) + long groupId, long folderId, String[] mimeTypes, int start, int end, + OrderByComparator obc) throws SystemException { List folderIds = new ArrayList(); diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFolderLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFolderLocalServiceImpl.java index 3899d69979fbfd..009ad2f0bc6d50 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFolderLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFolderLocalServiceImpl.java @@ -411,10 +411,9 @@ public DLFolder moveFolder( } public DLFolder updateFolder( - long folderId, long parentFolderId, String name, - String description, long defaultFileEntryTypeId, - List fileEntryTypeIds, boolean overrideFileEntryTypes, - ServiceContext serviceContext) + long folderId, long parentFolderId, String name, String description, + long defaultFileEntryTypeId, List fileEntryTypeIds, + boolean overrideFileEntryTypes, ServiceContext serviceContext) throws PortalException, SystemException { // File entry types diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFolderServiceImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFolderServiceImpl.java index 5567cff9e6412d..a9408297461489 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFolderServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLFolderServiceImpl.java @@ -495,8 +495,8 @@ protected Lock doLockFolder( } return lockLocalService.lock( - getUserId(), DLFolder.class.getName(), folderId, owner, - inheritable, expirationTime); + getUserId(), DLFolder.class.getName(), folderId, owner, inheritable, + expirationTime); } protected void doUnlockFolder(long groupId, long folderId, String lockUuid) diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLSyncServiceImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLSyncServiceImpl.java index ac175e868aa7ab..6022613082cfcf 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLSyncServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/service/impl/DLSyncServiceImpl.java @@ -148,8 +148,8 @@ public InputStream getFileDeltaAsStream( deltaOutputStreamWritableByteChannel); DeltaUtil.delta( - destinationReadableByteChannel, - checksumsByteChannelReader, deltaByteChannelWriter); + destinationReadableByteChannel, checksumsByteChannelReader, + deltaByteChannelWriter); deltaByteChannelWriter.finish(); diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/service/permission/DLFolderPermission.java b/portal-impl/src/com/liferay/portlet/documentlibrary/service/permission/DLFolderPermission.java index d9096cec767467..d4e4bcd9fdcd3c 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/service/permission/DLFolderPermission.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/service/permission/DLFolderPermission.java @@ -44,8 +44,7 @@ public static void check( } public static void check( - PermissionChecker permissionChecker, Folder folder, - String actionId) + PermissionChecker permissionChecker, Folder folder, String actionId) throws PortalException, SystemException { if (!folder.containsPermission(permissionChecker, actionId)) { diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/service/persistence/DLFolderFinderImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/service/persistence/DLFolderFinderImpl.java index ed500a1aefa29e..9bfd0f1e80bb76 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/service/persistence/DLFolderFinderImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/service/persistence/DLFolderFinderImpl.java @@ -686,8 +686,7 @@ protected String getFileShortcutsSQL( ((mimeTypes != null) && (mimeTypes.length > 0))) { sql = StringUtil.replace( - sql, "[$JOIN$]", - CustomSQLUtil.get(JOIN_FS_BY_DL_FILE_ENTRY)); + sql, "[$JOIN$]", CustomSQLUtil.get(JOIN_FS_BY_DL_FILE_ENTRY)); } else { sql = StringUtil.replace(sql, "[$JOIN$]", ""); diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/store/CMISStore.java b/portal-impl/src/com/liferay/portlet/documentlibrary/store/CMISStore.java index 9ebfbbf416f07f..0d6995154d7004 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/store/CMISStore.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/store/CMISStore.java @@ -586,8 +586,7 @@ private static class SessionHolder { Locale locale = LocaleUtil.getDefault(); parameters.put( - SessionParameter.LOCALE_ISO3166_COUNTRY, - locale.getCountry()); + SessionParameter.LOCALE_ISO3166_COUNTRY, locale.getCountry()); parameters.put( SessionParameter.LOCALE_ISO639_LANGUAGE, locale.getLanguage()); parameters.put( diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/store/DLStoreImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/store/DLStoreImpl.java index fe82316abeaa76..4f181d11b9f747 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/store/DLStoreImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/store/DLStoreImpl.java @@ -404,8 +404,8 @@ public void updateFile( throws PortalException, SystemException { validate( - fileName, fileExtension, sourceFileName, - validateFileExtension, file); + fileName, fileExtension, sourceFileName, validateFileExtension, + file); if (!PropsValues.DL_STORE_ANTIVIRUS_ENABLED) { AntivirusScannerUtil.scan(file); @@ -434,8 +434,7 @@ public void updateFile( } validate( - fileName, fileExtension, sourceFileName, - validateFileExtension, is); + fileName, fileExtension, sourceFileName, validateFileExtension, is); if (!PropsValues.DL_STORE_ANTIVIRUS_ENABLED || !AntivirusScannerUtil.isActive()) { diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/store/StoreFactory.java b/portal-impl/src/com/liferay/portlet/documentlibrary/store/StoreFactory.java index bfb6c8ad2bf8b0..a5685cb03db7ae 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/store/StoreFactory.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/store/StoreFactory.java @@ -119,8 +119,7 @@ public static void setInstance(Store store) { FileSystemStore.class.getName() }, new String[] { - "com.liferay.documentlibrary.util.JCRHook", - JCRStore.class.getName() + "com.liferay.documentlibrary.util.JCRHook", JCRStore.class.getName() }, new String[] { "com.liferay.documentlibrary.util.S3Hook", S3Store.class.getName() diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/store/StoreProxyBean.java b/portal-impl/src/com/liferay/portlet/documentlibrary/store/StoreProxyBean.java index 708e85b8b16471..fba78674eee4a5 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/store/StoreProxyBean.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/store/StoreProxyBean.java @@ -155,8 +155,8 @@ public void reindex(String[] ids) { } public void updateFile( - long companyId, long repositoryId, - long newRepositoryId, String fileName) { + long companyId, long repositoryId, long newRepositoryId, + String fileName) { throw new UnsupportedOperationException(); } @@ -169,22 +169,22 @@ public void updateFile( } public void updateFile( - long companyId, long repositoryId, String fileName, - String versionLabel, byte[] bytes) { + long companyId, long repositoryId, String fileName, String versionLabel, + byte[] bytes) { throw new UnsupportedOperationException(); } public void updateFile( - long companyId, long repositoryId, String fileName, - String versionLabel, File file) { + long companyId, long repositoryId, String fileName, String versionLabel, + File file) { throw new UnsupportedOperationException(); } public void updateFile( - long companyId, long repositoryId, String fileName, - String versionLabel, InputStream is) { + long companyId, long repositoryId, String fileName, String versionLabel, + InputStream is) { throw new UnsupportedOperationException(); } diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/util/DLIndexer.java b/portal-impl/src/com/liferay/portlet/documentlibrary/util/DLIndexer.java index ad0d349c811266..2f044516c01ff1 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/util/DLIndexer.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/util/DLIndexer.java @@ -574,8 +574,8 @@ protected void reindexFolders( long folderId = dlFolder.getFolderId(); String[] newIds = { - String.valueOf(companyId), portletId, - String.valueOf(groupId), String.valueOf(folderId) + String.valueOf(companyId), portletId, String.valueOf(groupId), + String.valueOf(folderId) }; reindex(newIds); @@ -607,8 +607,8 @@ protected void reindexRoot(long companyId, int groupStart, int groupEnd) long folderId = groupId; String[] newIds = { - String.valueOf(companyId), portletId, - String.valueOf(groupId), String.valueOf(folderId) + String.valueOf(companyId), portletId, String.valueOf(groupId), + String.valueOf(folderId) }; reindex(newIds); diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/util/ImageProcessorImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/util/ImageProcessorImpl.java index d835b256e173c4..5fe7aace88659b 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/util/ImageProcessorImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/util/ImageProcessorImpl.java @@ -142,8 +142,8 @@ public boolean isSupported(String mimeType) { public void storeThumbnail( long companyId, long groupId, long fileEntryId, long fileVersionId, - long custom1ImageId, long custom2ImageId, - InputStream is, String type) + long custom1ImageId, long custom2ImageId, InputStream is, + String type) throws Exception { _instance._storeThumbnail( diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/util/RawMetadataProcessorImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/util/RawMetadataProcessorImpl.java index e9b218d6f83621..1994365de70e6b 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/util/RawMetadataProcessorImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/util/RawMetadataProcessorImpl.java @@ -79,8 +79,7 @@ public void generateMetadata(FileVersion fileVersion) long fileEntryMetadataCount = DLFileEntryMetadataLocalServiceUtil.getFileEntryMetadataCount( - fileVersion.getFileEntryId(), - fileVersion.getFileVersionId()); + fileVersion.getFileEntryId(), fileVersion.getFileVersionId()); if (fileEntryMetadataCount == 0) { _instance.trigger(fileVersion); @@ -133,8 +132,8 @@ public void saveMetadata(FileVersion fileVersion) List ddmStructures = DDMStructureLocalServiceUtil.getClassStructures( - PortalUtil.getClassNameId(DLFileEntry.class), - QueryUtil.ALL_POS, QueryUtil.ALL_POS); + PortalUtil.getClassNameId(DLFileEntry.class), QueryUtil.ALL_POS, + QueryUtil.ALL_POS); ServiceContext serviceContext = new ServiceContext(); diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/util/VideoProcessorImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/util/VideoProcessorImpl.java index 87cb0eb697f06b..f10eb39c90b458 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/util/VideoProcessorImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/util/VideoProcessorImpl.java @@ -227,8 +227,7 @@ protected void exportPreviews( if (previewType.equals("mp4") || previewType.equals("ogv")) { exportPreview( portletDataContext, fileEntry, fileEntryElement, - "bin-path-video-preview-" + previewType, - previewType); + "bin-path-video-preview-" + previewType, previewType); } } } @@ -280,10 +279,8 @@ protected void importPreviews( if (previewType.equals("mp4") || previewType.equals("ogv")) { if (!portletDataContext.isPerformDirectBinaryImport()) { importPreviewFromLAR( - portletDataContext, importedFileEntry, - fileEntryElement, - "bin-path-video-preview-" + previewType, - previewType); + portletDataContext, importedFileEntry, fileEntryElement, + "bin-path-video-preview-" + previewType, previewType); } else { FileVersion importedFileVersion = @@ -387,8 +384,8 @@ private void _generateThumbnailXuggler( ServerDetector.getServerId(), PropsUtil.get(PropsKeys.LIFERAY_HOME), Log4JUtil.getCustomLogSettings(), - file.getCanonicalPath(), - thumbnailTempFile, THUMBNAIL_TYPE, height, width, + file.getCanonicalPath(), thumbnailTempFile, + THUMBNAIL_TYPE, height, width, PropsValues. DL_FILE_ENTRY_THUMBNAIL_VIDEO_FRAME_PERCENTAGE); diff --git a/portal-impl/src/com/liferay/portlet/documentlibrary/webdav/DLWebDAVStorageImpl.java b/portal-impl/src/com/liferay/portlet/documentlibrary/webdav/DLWebDAVStorageImpl.java index 0a46b39743f668..f137783ab9d768 100644 --- a/portal-impl/src/com/liferay/portlet/documentlibrary/webdav/DLWebDAVStorageImpl.java +++ b/portal-impl/src/com/liferay/portlet/documentlibrary/webdav/DLWebDAVStorageImpl.java @@ -1,988 +1,987 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portlet.documentlibrary.webdav; - -import com.liferay.portal.DuplicateLockException; -import com.liferay.portal.InvalidLockException; -import com.liferay.portal.NoSuchLockException; -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.repository.model.FileEntry; -import com.liferay.portal.kernel.repository.model.Folder; -import com.liferay.portal.kernel.servlet.HttpHeaders; -import com.liferay.portal.kernel.util.ContentTypes; -import com.liferay.portal.kernel.util.FileUtil; -import com.liferay.portal.kernel.util.GetterUtil; -import com.liferay.portal.kernel.util.MimeTypesUtil; -import com.liferay.portal.kernel.util.StringPool; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.kernel.webdav.BaseResourceImpl; -import com.liferay.portal.kernel.webdav.BaseWebDAVStorageImpl; -import com.liferay.portal.kernel.webdav.Resource; -import com.liferay.portal.kernel.webdav.Status; -import com.liferay.portal.kernel.webdav.WebDAVException; -import com.liferay.portal.kernel.webdav.WebDAVRequest; -import com.liferay.portal.kernel.webdav.WebDAVUtil; -import com.liferay.portal.kernel.workflow.WorkflowConstants; -import com.liferay.portal.model.Lock; -import com.liferay.portal.security.auth.PrincipalException; -import com.liferay.portal.service.ServiceContext; -import com.liferay.portal.service.ServiceContextFactory; -import com.liferay.portal.webdav.LockException; -import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil; -import com.liferay.portlet.documentlibrary.DuplicateFileException; -import com.liferay.portlet.documentlibrary.DuplicateFolderNameException; -import com.liferay.portlet.documentlibrary.NoSuchFileEntryException; -import com.liferay.portlet.documentlibrary.NoSuchFolderException; -import com.liferay.portlet.documentlibrary.model.DLFolderConstants; -import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil; - -import java.io.File; -import java.io.InputStream; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * @author Brian Wing Shun Chan - * @author Alexander Chow - */ -public class DLWebDAVStorageImpl extends BaseWebDAVStorageImpl { - - @Override - public int copyCollectionResource( - WebDAVRequest webDavRequest, Resource resource, String destination, - boolean overwrite, long depth) - throws WebDAVException { - - try { - String[] destinationArray = WebDAVUtil.getPathArray( - destination, true); - - long companyId = webDavRequest.getCompanyId(); - - long parentFolderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID; - - try { - parentFolderId = getParentFolderId(companyId, destinationArray); - } - catch (NoSuchFolderException nsfe) { - return HttpServletResponse.SC_CONFLICT; - } - - Folder folder = (Folder)resource.getModel(); - - long groupId = WebDAVUtil.getGroupId(companyId, destination); - String name = WebDAVUtil.getResourceName(destinationArray); - String description = folder.getDescription(); - - ServiceContext serviceContext = new ServiceContext(); - - serviceContext.setAddGroupPermissions( - isAddGroupPermissions(groupId)); - serviceContext.setAddGuestPermissions(true); - - int status = HttpServletResponse.SC_CREATED; - - if (overwrite) { - if (deleteResource( - groupId, parentFolderId, name, - webDavRequest.getLockUuid())) { - - status = HttpServletResponse.SC_NO_CONTENT; - } - } - - if (depth == 0) { - DLAppServiceUtil.addFolder( - groupId, parentFolderId, name, description, serviceContext); - } - else { - DLAppServiceUtil.copyFolder( - groupId, folder.getFolderId(), parentFolderId, name, - description, serviceContext); - } - - return status; - } - catch (DuplicateFolderNameException dfne) { - return HttpServletResponse.SC_PRECONDITION_FAILED; - } - catch (PrincipalException pe) { - return HttpServletResponse.SC_FORBIDDEN; - } - catch (Exception e) { - throw new WebDAVException(e); - } - } - - @Override - public int copySimpleResource( - WebDAVRequest webDavRequest, Resource resource, String destination, - boolean overwrite) - throws WebDAVException { - - File file = null; - - try { - String[] destinationArray = WebDAVUtil.getPathArray( - destination, true); - - long companyId = webDavRequest.getCompanyId(); - - long parentFolderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID; - - try { - parentFolderId = getParentFolderId(companyId, destinationArray); - } - catch (NoSuchFolderException nsfe) { - return HttpServletResponse.SC_CONFLICT; - } - - FileEntry fileEntry = (FileEntry)resource.getModel(); - - long groupId = WebDAVUtil.getGroupId(companyId, destination); - String mimeType = fileEntry.getMimeType(); - String title = WebDAVUtil.getResourceName(destinationArray); - String description = fileEntry.getDescription(); - String changeLog = StringPool.BLANK; - - InputStream is = fileEntry.getContentStream(); - - file = FileUtil.createTempFile(is); - - ServiceContext serviceContext = new ServiceContext(); - - serviceContext.setAddGroupPermissions( - isAddGroupPermissions(groupId)); - serviceContext.setAddGuestPermissions(true); - - int status = HttpServletResponse.SC_CREATED; - - if (overwrite) { - if (deleteResource( - groupId, parentFolderId, title, - webDavRequest.getLockUuid())) { - - status = HttpServletResponse.SC_NO_CONTENT; - } - } - - DLAppServiceUtil.addFileEntry( - groupId, parentFolderId, title, mimeType, title, description, - changeLog, file, serviceContext); - - return status; - } - catch (DuplicateFileException dfe) { - return HttpServletResponse.SC_PRECONDITION_FAILED; - } - catch (DuplicateFolderNameException dfne) { - return HttpServletResponse.SC_PRECONDITION_FAILED; - } - catch (LockException le) { - return WebDAVUtil.SC_LOCKED; - } - catch (PrincipalException pe) { - return HttpServletResponse.SC_FORBIDDEN; - } - catch (Exception e) { - throw new WebDAVException(e); - } - finally { - FileUtil.delete(file); - } - } - - @Override - public int deleteResource(WebDAVRequest webDavRequest) - throws WebDAVException { - - try { - Resource resource = getResource(webDavRequest); - - if (resource == null) { - if (webDavRequest.isAppleDoubleRequest()) { - return HttpServletResponse.SC_NO_CONTENT; - } - else { - return HttpServletResponse.SC_NOT_FOUND; - } - } - - Object model = resource.getModel(); - - if (model instanceof Folder) { - Folder folder = (Folder)model; - - DLAppServiceUtil.deleteFolder(folder.getFolderId()); - } - else { - FileEntry fileEntry = (FileEntry)model; - - if (!hasLock(fileEntry, webDavRequest.getLockUuid()) && - (fileEntry.getLock() != null)) { - - return WebDAVUtil.SC_LOCKED; - } - - DLAppServiceUtil.deleteFileEntry(fileEntry.getFileEntryId()); - } - - return HttpServletResponse.SC_NO_CONTENT; - } - catch (PrincipalException pe) { - return HttpServletResponse.SC_FORBIDDEN; - } - catch (Exception e) { - throw new WebDAVException(e); - } - } - - public Resource getResource(WebDAVRequest webDavRequest) - throws WebDAVException { - - try { - String[] pathArray = webDavRequest.getPathArray(); - - long companyId = webDavRequest.getCompanyId(); - long parentFolderId = getParentFolderId(companyId, pathArray); - String name = WebDAVUtil.getResourceName(pathArray); - - if (Validator.isNull(name)) { - String path = getRootPath() + webDavRequest.getPath(); - - return new BaseResourceImpl(path, StringPool.BLANK, getToken()); - } - - try { - Folder folder = DLAppServiceUtil.getFolder( - webDavRequest.getGroupId(), parentFolderId, name); - - if ((folder.getParentFolderId() != parentFolderId) || - (webDavRequest.getGroupId() != folder.getRepositoryId())) { - - throw new NoSuchFolderException(); - } - - return toResource(webDavRequest, folder, false); - } - catch (NoSuchFolderException nsfe) { - try { - String titleWithExtension = name; - - FileEntry fileEntry = DLAppServiceUtil.getFileEntry( - webDavRequest.getGroupId(), parentFolderId, - titleWithExtension); - - return toResource(webDavRequest, fileEntry, false); - } - catch (NoSuchFileEntryException nsfee) { - return null; - } - } - } - catch (Exception e) { - throw new WebDAVException(e); - } - } - - public List getResources(WebDAVRequest webDavRequest) - throws WebDAVException { - - try { - long folderId = getFolderId( - webDavRequest.getCompanyId(), webDavRequest.getPathArray()); - - List folders = getFolders(webDavRequest, folderId); - List fileEntries = getFileEntries( - webDavRequest, folderId); - - List resources = new ArrayList( - folders.size() + fileEntries.size()); - - resources.addAll(folders); - resources.addAll(fileEntries); - - return resources; - } - catch (Exception e) { - throw new WebDAVException(e); - } - } - - @Override - public boolean isSupportsClassTwo() { - return true; - } - - @Override - public Status lockResource( - WebDAVRequest webDavRequest, String owner, long timeout) - throws WebDAVException { - - Resource resource = getResource(webDavRequest); - - Lock lock = null; - int status = HttpServletResponse.SC_OK; - - try { - if (resource == null) { - status = HttpServletResponse.SC_CREATED; - - HttpServletRequest request = - webDavRequest.getHttpServletRequest(); - - String[] pathArray = webDavRequest.getPathArray(); - - long companyId = webDavRequest.getCompanyId(); - long groupId = webDavRequest.getGroupId(); - long parentFolderId = getParentFolderId(companyId, pathArray); - String title = WebDAVUtil.getResourceName(pathArray); - - String contentType = GetterUtil.get( - request.getHeader(HttpHeaders.CONTENT_TYPE), - ContentTypes.APPLICATION_OCTET_STREAM); - - if (contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) { - contentType = MimeTypesUtil.getContentType( - request.getInputStream(), title); - } - - String description = StringPool.BLANK; - String changeLog = StringPool.BLANK; - - File file = FileUtil.createTempFile( - FileUtil.getExtension(title)); - - file.createNewFile(); - - ServiceContext serviceContext = new ServiceContext(); - - serviceContext.setAddGroupPermissions( - isAddGroupPermissions(groupId)); - serviceContext.setAddGuestPermissions(true); - - FileEntry fileEntry = DLAppServiceUtil.addFileEntry( - groupId, parentFolderId, title, contentType, title, - description, changeLog, file, serviceContext); - - resource = toResource(webDavRequest, fileEntry, false); - } - - if (resource instanceof DLFileEntryResourceImpl) { - FileEntry fileEntry = (FileEntry)resource.getModel(); - - lock = DLAppServiceUtil.lockFileEntry( - fileEntry.getFileEntryId(), owner, timeout); - } - else { - boolean inheritable = false; - - long depth = WebDAVUtil.getDepth( - webDavRequest.getHttpServletRequest()); - - if (depth != 0) { - inheritable = true; - } - - Folder folder = (Folder)resource.getModel(); - - lock = DLAppServiceUtil.lockFolder( - folder.getRepositoryId(), folder.getFolderId(), owner, - inheritable, timeout); - } - } - catch (Exception e) { - - // DuplicateLock is 423 not 501 - - if (!(e instanceof DuplicateLockException)) { - throw new WebDAVException(e); - } - - status = WebDAVUtil.SC_LOCKED; - } - - return new Status(lock, status); - } - - @Override - public Status makeCollection(WebDAVRequest webDavRequest) - throws WebDAVException { - - try { - HttpServletRequest request = webDavRequest.getHttpServletRequest(); - - if (request.getContentLength() > 0) { - return new Status( - HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); - } - - String[] pathArray = webDavRequest.getPathArray(); - - long companyId = webDavRequest.getCompanyId(); - long groupId = webDavRequest.getGroupId(); - long parentFolderId = getParentFolderId(companyId, pathArray); - String name = WebDAVUtil.getResourceName(pathArray); - String description = StringPool.BLANK; - - ServiceContext serviceContext = new ServiceContext(); - - serviceContext.setAddGroupPermissions( - isAddGroupPermissions(groupId)); - serviceContext.setAddGuestPermissions(true); - - DLAppServiceUtil.addFolder( - groupId, parentFolderId, name, description, serviceContext); - - String location = StringUtil.merge(pathArray, StringPool.SLASH); - - return new Status(location, HttpServletResponse.SC_CREATED); - } - catch (DuplicateFolderNameException dfne) { - return new Status(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - } - catch (DuplicateFileException dfe) { - return new Status(HttpServletResponse.SC_METHOD_NOT_ALLOWED); - } - catch (NoSuchFolderException nsfe) { - return new Status(HttpServletResponse.SC_CONFLICT); - } - catch (PrincipalException pe) { - return new Status(HttpServletResponse.SC_FORBIDDEN); - } - catch (Exception e) { - throw new WebDAVException(e); - } - } - - @Override - public int moveCollectionResource( - WebDAVRequest webDavRequest, Resource resource, String destination, - boolean overwrite) - throws WebDAVException { - - try { - String[] destinationArray = WebDAVUtil.getPathArray( - destination, true); - - Folder folder = (Folder)resource.getModel(); - - long companyId = webDavRequest.getCompanyId(); - long groupId = WebDAVUtil.getGroupId(companyId, destinationArray); - long folderId = folder.getFolderId(); - long parentFolderId = getParentFolderId( - companyId, destinationArray); - String name = WebDAVUtil.getResourceName(destinationArray); - String description = folder.getDescription(); - - ServiceContext serviceContext = new ServiceContext(); - - int status = HttpServletResponse.SC_CREATED; - - if (overwrite) { - if (deleteResource( - groupId, parentFolderId, name, - webDavRequest.getLockUuid())) { - - status = HttpServletResponse.SC_NO_CONTENT; - } - } - - if (parentFolderId != folder.getParentFolderId()) { - DLAppServiceUtil.moveFolder( - folderId, parentFolderId, serviceContext); - } - - if (!name.equals(folder.getName())) { - DLAppServiceUtil.updateFolder( - folderId, name, description, serviceContext); - } - - return status; - } - catch (PrincipalException pe) { - return HttpServletResponse.SC_FORBIDDEN; - } - catch (DuplicateFolderNameException dfne) { - return HttpServletResponse.SC_PRECONDITION_FAILED; - } - catch (Exception e) { - throw new WebDAVException(e); - } - } - - @Override - public int moveSimpleResource( - WebDAVRequest webDavRequest, Resource resource, String destination, - boolean overwrite) - throws WebDAVException { - - File file = null; - - try { - String[] destinationArray = WebDAVUtil.getPathArray( - destination, true); - - FileEntry fileEntry = (FileEntry)resource.getModel(); - - if (!hasLock(fileEntry, webDavRequest.getLockUuid()) && - (fileEntry.getLock() != null)) { - - return WebDAVUtil.SC_LOCKED; - } - - long companyId = webDavRequest.getCompanyId(); - long groupId = WebDAVUtil.getGroupId(companyId, destinationArray); - long newParentFolderId = getParentFolderId( - companyId, destinationArray); - String sourceFileName = WebDAVUtil.getResourceName( - destinationArray); - String title = WebDAVUtil.getResourceName(destinationArray); - String description = fileEntry.getDescription(); - String changeLog = StringPool.BLANK; - - String[] assetTagNames = AssetTagLocalServiceUtil.getTagNames( - FileEntry.class.getName(), fileEntry.getFileEntryId()); - - ServiceContext serviceContext = new ServiceContext(); - - serviceContext.setAssetTagNames(assetTagNames); - - int status = HttpServletResponse.SC_CREATED; - - if (overwrite) { - if (deleteResource( - groupId, newParentFolderId, title, - webDavRequest.getLockUuid())) { - - status = HttpServletResponse.SC_NO_CONTENT; - } - } - - // LPS-5415 - - if (webDavRequest.isMac()) { - try { - FileEntry destFileEntry = DLAppServiceUtil.getFileEntry( - groupId, newParentFolderId, title); - - InputStream is = fileEntry.getContentStream(); - - file = FileUtil.createTempFile(is); - - DLAppServiceUtil.updateFileEntry( - destFileEntry.getFileEntryId(), - destFileEntry.getTitle(), destFileEntry.getMimeType(), - destFileEntry.getTitle(), - destFileEntry.getDescription(), changeLog, false, file, - serviceContext); - - DLAppServiceUtil.deleteFileEntry( - fileEntry.getFileEntryId()); - - return status; - } - catch (NoSuchFileEntryException nsfee) { - } - } - - DLAppServiceUtil.updateFileEntry( - fileEntry.getFileEntryId(), sourceFileName, - fileEntry.getMimeType(), title, description, changeLog, false, - file, serviceContext); - - if (fileEntry.getFolderId() != newParentFolderId) { - fileEntry = DLAppServiceUtil.moveFileEntry( - fileEntry.getFileEntryId(), newParentFolderId, - serviceContext); - } - - return status; - } - catch (PrincipalException pe) { - return HttpServletResponse.SC_FORBIDDEN; - } - catch (DuplicateFileException dfe) { - return HttpServletResponse.SC_PRECONDITION_FAILED; - } - catch (DuplicateFolderNameException dfne) { - return HttpServletResponse.SC_PRECONDITION_FAILED; - } - catch (LockException le) { - return WebDAVUtil.SC_LOCKED; - } - catch (Exception e) { - throw new WebDAVException(e); - } - finally { - FileUtil.delete(file); - } - } - - @Override - public int putResource(WebDAVRequest webDavRequest) throws WebDAVException { - File file = null; - - try { - HttpServletRequest request = webDavRequest.getHttpServletRequest(); - - String[] pathArray = webDavRequest.getPathArray(); - - long companyId = webDavRequest.getCompanyId(); - long groupId = webDavRequest.getGroupId(); - long parentFolderId = getParentFolderId(companyId, pathArray); - String title = WebDAVUtil.getResourceName(pathArray); - String description = StringPool.BLANK; - String changeLog = StringPool.BLANK; - - ServiceContext serviceContext = ServiceContextFactory.getInstance( - request); - - serviceContext.setAddGroupPermissions( - isAddGroupPermissions(groupId)); - serviceContext.setAddGuestPermissions(true); - - String contentType = GetterUtil.get( - request.getHeader(HttpHeaders.CONTENT_TYPE), - ContentTypes.APPLICATION_OCTET_STREAM); - - String extension = FileUtil.getExtension(title); - - file = FileUtil.createTempFile(extension); - - FileUtil.write(file, request.getInputStream()); - - if (contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) { - contentType = MimeTypesUtil.getContentType(file, title); - } - - try { - FileEntry fileEntry = DLAppServiceUtil.getFileEntry( - groupId, parentFolderId, title); - - if (!hasLock(fileEntry, webDavRequest.getLockUuid()) && - (fileEntry.getLock() != null)) { - - return WebDAVUtil.SC_LOCKED; - } - - long fileEntryId = fileEntry.getFileEntryId(); - - description = fileEntry.getDescription(); - - String[] assetTagNames = AssetTagLocalServiceUtil.getTagNames( - FileEntry.class.getName(), fileEntry.getFileEntryId()); - - serviceContext.setAssetTagNames(assetTagNames); - - DLAppServiceUtil.updateFileEntry( - fileEntryId, title, contentType, title, description, - changeLog, false, file, serviceContext); - } - catch (NoSuchFileEntryException nsfee) { - if (file.length() == 0) { - serviceContext.setWorkflowAction( - WorkflowConstants.ACTION_SAVE_DRAFT); - } - - DLAppServiceUtil.addFileEntry( - groupId, parentFolderId, title, contentType, title, - description, changeLog, file, serviceContext); - } - - if (_log.isInfoEnabled()) { - _log.info( - "Added " + StringUtil.merge(pathArray, StringPool.SLASH)); - } - - return HttpServletResponse.SC_CREATED; - } - catch (PrincipalException pe) { - return HttpServletResponse.SC_FORBIDDEN; - } - catch (NoSuchFolderException nsfe) { - return HttpServletResponse.SC_CONFLICT; - } - catch (PortalException pe) { - if (_log.isWarnEnabled()) { - _log.warn(pe, pe); - } - - return HttpServletResponse.SC_CONFLICT; - } - catch (Exception e) { - throw new WebDAVException(e); - } - finally { - FileUtil.delete(file); - } - } - - @Override - public Lock refreshResourceLock( - WebDAVRequest webDavRequest, String uuid, long timeout) - throws WebDAVException { - - Resource resource = getResource(webDavRequest); - - Lock lock = null; - - try { - if (resource instanceof DLFileEntryResourceImpl) { - lock = DLAppServiceUtil.refreshFileEntryLock(uuid, timeout); - } - else { - lock = DLAppServiceUtil.refreshFolderLock(uuid, timeout); - } - } - catch (Exception e) { - throw new WebDAVException(e); - } - - return lock; - } - - @Override - public boolean unlockResource(WebDAVRequest webDavRequest, String token) - throws WebDAVException { - - Resource resource = getResource(webDavRequest); - - try { - if (resource instanceof DLFileEntryResourceImpl) { - FileEntry fileEntry = (FileEntry)resource.getModel(); - - DLAppServiceUtil.unlockFileEntry( - fileEntry.getFileEntryId(), token); - - if (webDavRequest.isAppleDoubleRequest()) { - DLAppServiceUtil.deleteFileEntry( - fileEntry.getFileEntryId()); - } - } - else { - Folder folder = (Folder)resource.getModel(); - - DLAppServiceUtil.unlockFolder( - folder.getRepositoryId(), folder.getParentFolderId(), - folder.getName(), token); - } - - return true; - } - catch (Exception e) { - if (e instanceof InvalidLockException) { - if (_log.isWarnEnabled()) { - _log.warn(e.getMessage()); - } - } - else { - if (_log.isWarnEnabled()) { - _log.warn("Unable to unlock file entry", e); - } - } - } - - return false; - } - - protected boolean deleteResource( - long groupId, long parentFolderId, String name, String lockUuid) - throws Exception { - - try { - Folder folder = DLAppServiceUtil.getFolder( - groupId, parentFolderId, name); - - DLAppServiceUtil.deleteFolder(folder.getFolderId()); - - return true; - } - catch (NoSuchFolderException nsfe) { - try { - FileEntry fileEntry = DLAppServiceUtil.getFileEntry( - groupId, parentFolderId, name); - - if (!hasLock(fileEntry, lockUuid) && - (fileEntry.getLock() != null)) { - - throw new LockException(); - } - - DLAppServiceUtil.deleteFileEntryByTitle( - groupId, parentFolderId, name); - - return true; - } - catch (NoSuchFileEntryException nsfee) { - } - } - - return false; - } - - protected List getFileEntries( - WebDAVRequest webDavRequest, long parentFolderId) - throws Exception { - - List resources = new ArrayList(); - - List fileEntries = DLAppServiceUtil.getFileEntries( - webDavRequest.getGroupId(), parentFolderId); - - for (FileEntry fileEntry : fileEntries) { - Resource resource = toResource(webDavRequest, fileEntry, true); - - resources.add(resource); - } - - return resources; - } - - protected long getFolderId(long companyId, String[] pathArray) - throws Exception { - - return getFolderId(companyId, pathArray, false); - } - - protected long getFolderId( - long companyId, String[] pathArray, boolean parent) - throws Exception { - - long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID; - - if (pathArray.length <= 1) { - return folderId; - } - else { - long groupId = WebDAVUtil.getGroupId(companyId, pathArray); - - int x = pathArray.length; - - if (parent) { - x--; - } - - for (int i = 2; i < x; i++) { - String name = pathArray[i]; - - Folder folder = DLAppServiceUtil.getFolder( - groupId, folderId, name); - - if (groupId == folder.getRepositoryId()) { - folderId = folder.getFolderId(); - } - } - } - - return folderId; - } - - protected List getFolders( - WebDAVRequest webDavRequest, long parentFolderId) - throws Exception { - - List resources = new ArrayList(); - - long groupId = webDavRequest.getGroupId(); - - List folders = DLAppServiceUtil.getFolders( - groupId, parentFolderId, false); - - for (Folder folder : folders) { - Resource resource = toResource(webDavRequest, folder, true); - - resources.add(resource); - } - - return resources; - } - - protected long getParentFolderId(long companyId, String[] pathArray) - throws Exception { - - return getFolderId(companyId, pathArray, true); - } - - protected boolean hasLock(FileEntry fileEntry, String lockUuid) - throws Exception { - - if (Validator.isNull(lockUuid)) { - - // Client does not claim to know of a lock - - return fileEntry.hasLock(); - } - else { - - // Client claims to know of a lock. Verify the lock UUID. - - try { - return DLAppServiceUtil.verifyFileEntryLock( - fileEntry.getRepositoryId(), fileEntry.getFileEntryId(), - lockUuid); - } - catch (NoSuchLockException nsle) { - return false; - } - } - } - - protected Resource toResource( - WebDAVRequest webDavRequest, FileEntry fileEntry, - boolean appendPath) { - - String parentPath = getRootPath() + webDavRequest.getPath(); - String name = StringPool.BLANK; - - if (appendPath) { - name = fileEntry.getTitle(); - } - - return new DLFileEntryResourceImpl( - webDavRequest, fileEntry, parentPath, name); - } - - protected Resource toResource( - WebDAVRequest webDavRequest, Folder folder, boolean appendPath) { - - String parentPath = getRootPath() + webDavRequest.getPath(); - String name = StringPool.BLANK; - - if (appendPath) { - name = folder.getName(); - } - - Resource resource = new BaseResourceImpl( - parentPath, name, folder.getName(), folder.getCreateDate(), - folder.getModifiedDate()); - - resource.setModel(folder); - resource.setClassName(Folder.class.getName()); - resource.setPrimaryKey(folder.getPrimaryKey()); - - return resource; - } - - private static Log _log = LogFactoryUtil.getLog(DLWebDAVStorageImpl.class); - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portlet.documentlibrary.webdav; + +import com.liferay.portal.DuplicateLockException; +import com.liferay.portal.InvalidLockException; +import com.liferay.portal.NoSuchLockException; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.repository.model.FileEntry; +import com.liferay.portal.kernel.repository.model.Folder; +import com.liferay.portal.kernel.servlet.HttpHeaders; +import com.liferay.portal.kernel.util.ContentTypes; +import com.liferay.portal.kernel.util.FileUtil; +import com.liferay.portal.kernel.util.GetterUtil; +import com.liferay.portal.kernel.util.MimeTypesUtil; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.kernel.webdav.BaseResourceImpl; +import com.liferay.portal.kernel.webdav.BaseWebDAVStorageImpl; +import com.liferay.portal.kernel.webdav.Resource; +import com.liferay.portal.kernel.webdav.Status; +import com.liferay.portal.kernel.webdav.WebDAVException; +import com.liferay.portal.kernel.webdav.WebDAVRequest; +import com.liferay.portal.kernel.webdav.WebDAVUtil; +import com.liferay.portal.kernel.workflow.WorkflowConstants; +import com.liferay.portal.model.Lock; +import com.liferay.portal.security.auth.PrincipalException; +import com.liferay.portal.service.ServiceContext; +import com.liferay.portal.service.ServiceContextFactory; +import com.liferay.portal.webdav.LockException; +import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil; +import com.liferay.portlet.documentlibrary.DuplicateFileException; +import com.liferay.portlet.documentlibrary.DuplicateFolderNameException; +import com.liferay.portlet.documentlibrary.NoSuchFileEntryException; +import com.liferay.portlet.documentlibrary.NoSuchFolderException; +import com.liferay.portlet.documentlibrary.model.DLFolderConstants; +import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil; + +import java.io.File; +import java.io.InputStream; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * @author Brian Wing Shun Chan + * @author Alexander Chow + */ +public class DLWebDAVStorageImpl extends BaseWebDAVStorageImpl { + + @Override + public int copyCollectionResource( + WebDAVRequest webDavRequest, Resource resource, String destination, + boolean overwrite, long depth) + throws WebDAVException { + + try { + String[] destinationArray = WebDAVUtil.getPathArray( + destination, true); + + long companyId = webDavRequest.getCompanyId(); + + long parentFolderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID; + + try { + parentFolderId = getParentFolderId(companyId, destinationArray); + } + catch (NoSuchFolderException nsfe) { + return HttpServletResponse.SC_CONFLICT; + } + + Folder folder = (Folder)resource.getModel(); + + long groupId = WebDAVUtil.getGroupId(companyId, destination); + String name = WebDAVUtil.getResourceName(destinationArray); + String description = folder.getDescription(); + + ServiceContext serviceContext = new ServiceContext(); + + serviceContext.setAddGroupPermissions( + isAddGroupPermissions(groupId)); + serviceContext.setAddGuestPermissions(true); + + int status = HttpServletResponse.SC_CREATED; + + if (overwrite) { + if (deleteResource( + groupId, parentFolderId, name, + webDavRequest.getLockUuid())) { + + status = HttpServletResponse.SC_NO_CONTENT; + } + } + + if (depth == 0) { + DLAppServiceUtil.addFolder( + groupId, parentFolderId, name, description, serviceContext); + } + else { + DLAppServiceUtil.copyFolder( + groupId, folder.getFolderId(), parentFolderId, name, + description, serviceContext); + } + + return status; + } + catch (DuplicateFolderNameException dfne) { + return HttpServletResponse.SC_PRECONDITION_FAILED; + } + catch (PrincipalException pe) { + return HttpServletResponse.SC_FORBIDDEN; + } + catch (Exception e) { + throw new WebDAVException(e); + } + } + + @Override + public int copySimpleResource( + WebDAVRequest webDavRequest, Resource resource, String destination, + boolean overwrite) + throws WebDAVException { + + File file = null; + + try { + String[] destinationArray = WebDAVUtil.getPathArray( + destination, true); + + long companyId = webDavRequest.getCompanyId(); + + long parentFolderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID; + + try { + parentFolderId = getParentFolderId(companyId, destinationArray); + } + catch (NoSuchFolderException nsfe) { + return HttpServletResponse.SC_CONFLICT; + } + + FileEntry fileEntry = (FileEntry)resource.getModel(); + + long groupId = WebDAVUtil.getGroupId(companyId, destination); + String mimeType = fileEntry.getMimeType(); + String title = WebDAVUtil.getResourceName(destinationArray); + String description = fileEntry.getDescription(); + String changeLog = StringPool.BLANK; + + InputStream is = fileEntry.getContentStream(); + + file = FileUtil.createTempFile(is); + + ServiceContext serviceContext = new ServiceContext(); + + serviceContext.setAddGroupPermissions( + isAddGroupPermissions(groupId)); + serviceContext.setAddGuestPermissions(true); + + int status = HttpServletResponse.SC_CREATED; + + if (overwrite) { + if (deleteResource( + groupId, parentFolderId, title, + webDavRequest.getLockUuid())) { + + status = HttpServletResponse.SC_NO_CONTENT; + } + } + + DLAppServiceUtil.addFileEntry( + groupId, parentFolderId, title, mimeType, title, description, + changeLog, file, serviceContext); + + return status; + } + catch (DuplicateFileException dfe) { + return HttpServletResponse.SC_PRECONDITION_FAILED; + } + catch (DuplicateFolderNameException dfne) { + return HttpServletResponse.SC_PRECONDITION_FAILED; + } + catch (LockException le) { + return WebDAVUtil.SC_LOCKED; + } + catch (PrincipalException pe) { + return HttpServletResponse.SC_FORBIDDEN; + } + catch (Exception e) { + throw new WebDAVException(e); + } + finally { + FileUtil.delete(file); + } + } + + @Override + public int deleteResource(WebDAVRequest webDavRequest) + throws WebDAVException { + + try { + Resource resource = getResource(webDavRequest); + + if (resource == null) { + if (webDavRequest.isAppleDoubleRequest()) { + return HttpServletResponse.SC_NO_CONTENT; + } + else { + return HttpServletResponse.SC_NOT_FOUND; + } + } + + Object model = resource.getModel(); + + if (model instanceof Folder) { + Folder folder = (Folder)model; + + DLAppServiceUtil.deleteFolder(folder.getFolderId()); + } + else { + FileEntry fileEntry = (FileEntry)model; + + if (!hasLock(fileEntry, webDavRequest.getLockUuid()) && + (fileEntry.getLock() != null)) { + + return WebDAVUtil.SC_LOCKED; + } + + DLAppServiceUtil.deleteFileEntry(fileEntry.getFileEntryId()); + } + + return HttpServletResponse.SC_NO_CONTENT; + } + catch (PrincipalException pe) { + return HttpServletResponse.SC_FORBIDDEN; + } + catch (Exception e) { + throw new WebDAVException(e); + } + } + + public Resource getResource(WebDAVRequest webDavRequest) + throws WebDAVException { + + try { + String[] pathArray = webDavRequest.getPathArray(); + + long companyId = webDavRequest.getCompanyId(); + long parentFolderId = getParentFolderId(companyId, pathArray); + String name = WebDAVUtil.getResourceName(pathArray); + + if (Validator.isNull(name)) { + String path = getRootPath() + webDavRequest.getPath(); + + return new BaseResourceImpl(path, StringPool.BLANK, getToken()); + } + + try { + Folder folder = DLAppServiceUtil.getFolder( + webDavRequest.getGroupId(), parentFolderId, name); + + if ((folder.getParentFolderId() != parentFolderId) || + (webDavRequest.getGroupId() != folder.getRepositoryId())) { + + throw new NoSuchFolderException(); + } + + return toResource(webDavRequest, folder, false); + } + catch (NoSuchFolderException nsfe) { + try { + String titleWithExtension = name; + + FileEntry fileEntry = DLAppServiceUtil.getFileEntry( + webDavRequest.getGroupId(), parentFolderId, + titleWithExtension); + + return toResource(webDavRequest, fileEntry, false); + } + catch (NoSuchFileEntryException nsfee) { + return null; + } + } + } + catch (Exception e) { + throw new WebDAVException(e); + } + } + + public List getResources(WebDAVRequest webDavRequest) + throws WebDAVException { + + try { + long folderId = getFolderId( + webDavRequest.getCompanyId(), webDavRequest.getPathArray()); + + List folders = getFolders(webDavRequest, folderId); + List fileEntries = getFileEntries( + webDavRequest, folderId); + + List resources = new ArrayList( + folders.size() + fileEntries.size()); + + resources.addAll(folders); + resources.addAll(fileEntries); + + return resources; + } + catch (Exception e) { + throw new WebDAVException(e); + } + } + + @Override + public boolean isSupportsClassTwo() { + return true; + } + + @Override + public Status lockResource( + WebDAVRequest webDavRequest, String owner, long timeout) + throws WebDAVException { + + Resource resource = getResource(webDavRequest); + + Lock lock = null; + int status = HttpServletResponse.SC_OK; + + try { + if (resource == null) { + status = HttpServletResponse.SC_CREATED; + + HttpServletRequest request = + webDavRequest.getHttpServletRequest(); + + String[] pathArray = webDavRequest.getPathArray(); + + long companyId = webDavRequest.getCompanyId(); + long groupId = webDavRequest.getGroupId(); + long parentFolderId = getParentFolderId(companyId, pathArray); + String title = WebDAVUtil.getResourceName(pathArray); + + String contentType = GetterUtil.get( + request.getHeader(HttpHeaders.CONTENT_TYPE), + ContentTypes.APPLICATION_OCTET_STREAM); + + if (contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) { + contentType = MimeTypesUtil.getContentType( + request.getInputStream(), title); + } + + String description = StringPool.BLANK; + String changeLog = StringPool.BLANK; + + File file = FileUtil.createTempFile( + FileUtil.getExtension(title)); + + file.createNewFile(); + + ServiceContext serviceContext = new ServiceContext(); + + serviceContext.setAddGroupPermissions( + isAddGroupPermissions(groupId)); + serviceContext.setAddGuestPermissions(true); + + FileEntry fileEntry = DLAppServiceUtil.addFileEntry( + groupId, parentFolderId, title, contentType, title, + description, changeLog, file, serviceContext); + + resource = toResource(webDavRequest, fileEntry, false); + } + + if (resource instanceof DLFileEntryResourceImpl) { + FileEntry fileEntry = (FileEntry)resource.getModel(); + + lock = DLAppServiceUtil.lockFileEntry( + fileEntry.getFileEntryId(), owner, timeout); + } + else { + boolean inheritable = false; + + long depth = WebDAVUtil.getDepth( + webDavRequest.getHttpServletRequest()); + + if (depth != 0) { + inheritable = true; + } + + Folder folder = (Folder)resource.getModel(); + + lock = DLAppServiceUtil.lockFolder( + folder.getRepositoryId(), folder.getFolderId(), owner, + inheritable, timeout); + } + } + catch (Exception e) { + + // DuplicateLock is 423 not 501 + + if (!(e instanceof DuplicateLockException)) { + throw new WebDAVException(e); + } + + status = WebDAVUtil.SC_LOCKED; + } + + return new Status(lock, status); + } + + @Override + public Status makeCollection(WebDAVRequest webDavRequest) + throws WebDAVException { + + try { + HttpServletRequest request = webDavRequest.getHttpServletRequest(); + + if (request.getContentLength() > 0) { + return new Status( + HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); + } + + String[] pathArray = webDavRequest.getPathArray(); + + long companyId = webDavRequest.getCompanyId(); + long groupId = webDavRequest.getGroupId(); + long parentFolderId = getParentFolderId(companyId, pathArray); + String name = WebDAVUtil.getResourceName(pathArray); + String description = StringPool.BLANK; + + ServiceContext serviceContext = new ServiceContext(); + + serviceContext.setAddGroupPermissions( + isAddGroupPermissions(groupId)); + serviceContext.setAddGuestPermissions(true); + + DLAppServiceUtil.addFolder( + groupId, parentFolderId, name, description, serviceContext); + + String location = StringUtil.merge(pathArray, StringPool.SLASH); + + return new Status(location, HttpServletResponse.SC_CREATED); + } + catch (DuplicateFolderNameException dfne) { + return new Status(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + } + catch (DuplicateFileException dfe) { + return new Status(HttpServletResponse.SC_METHOD_NOT_ALLOWED); + } + catch (NoSuchFolderException nsfe) { + return new Status(HttpServletResponse.SC_CONFLICT); + } + catch (PrincipalException pe) { + return new Status(HttpServletResponse.SC_FORBIDDEN); + } + catch (Exception e) { + throw new WebDAVException(e); + } + } + + @Override + public int moveCollectionResource( + WebDAVRequest webDavRequest, Resource resource, String destination, + boolean overwrite) + throws WebDAVException { + + try { + String[] destinationArray = WebDAVUtil.getPathArray( + destination, true); + + Folder folder = (Folder)resource.getModel(); + + long companyId = webDavRequest.getCompanyId(); + long groupId = WebDAVUtil.getGroupId(companyId, destinationArray); + long folderId = folder.getFolderId(); + long parentFolderId = getParentFolderId( + companyId, destinationArray); + String name = WebDAVUtil.getResourceName(destinationArray); + String description = folder.getDescription(); + + ServiceContext serviceContext = new ServiceContext(); + + int status = HttpServletResponse.SC_CREATED; + + if (overwrite) { + if (deleteResource( + groupId, parentFolderId, name, + webDavRequest.getLockUuid())) { + + status = HttpServletResponse.SC_NO_CONTENT; + } + } + + if (parentFolderId != folder.getParentFolderId()) { + DLAppServiceUtil.moveFolder( + folderId, parentFolderId, serviceContext); + } + + if (!name.equals(folder.getName())) { + DLAppServiceUtil.updateFolder( + folderId, name, description, serviceContext); + } + + return status; + } + catch (PrincipalException pe) { + return HttpServletResponse.SC_FORBIDDEN; + } + catch (DuplicateFolderNameException dfne) { + return HttpServletResponse.SC_PRECONDITION_FAILED; + } + catch (Exception e) { + throw new WebDAVException(e); + } + } + + @Override + public int moveSimpleResource( + WebDAVRequest webDavRequest, Resource resource, String destination, + boolean overwrite) + throws WebDAVException { + + File file = null; + + try { + String[] destinationArray = WebDAVUtil.getPathArray( + destination, true); + + FileEntry fileEntry = (FileEntry)resource.getModel(); + + if (!hasLock(fileEntry, webDavRequest.getLockUuid()) && + (fileEntry.getLock() != null)) { + + return WebDAVUtil.SC_LOCKED; + } + + long companyId = webDavRequest.getCompanyId(); + long groupId = WebDAVUtil.getGroupId(companyId, destinationArray); + long newParentFolderId = getParentFolderId( + companyId, destinationArray); + String sourceFileName = WebDAVUtil.getResourceName( + destinationArray); + String title = WebDAVUtil.getResourceName(destinationArray); + String description = fileEntry.getDescription(); + String changeLog = StringPool.BLANK; + + String[] assetTagNames = AssetTagLocalServiceUtil.getTagNames( + FileEntry.class.getName(), fileEntry.getFileEntryId()); + + ServiceContext serviceContext = new ServiceContext(); + + serviceContext.setAssetTagNames(assetTagNames); + + int status = HttpServletResponse.SC_CREATED; + + if (overwrite) { + if (deleteResource( + groupId, newParentFolderId, title, + webDavRequest.getLockUuid())) { + + status = HttpServletResponse.SC_NO_CONTENT; + } + } + + // LPS-5415 + + if (webDavRequest.isMac()) { + try { + FileEntry destFileEntry = DLAppServiceUtil.getFileEntry( + groupId, newParentFolderId, title); + + InputStream is = fileEntry.getContentStream(); + + file = FileUtil.createTempFile(is); + + DLAppServiceUtil.updateFileEntry( + destFileEntry.getFileEntryId(), + destFileEntry.getTitle(), destFileEntry.getMimeType(), + destFileEntry.getTitle(), + destFileEntry.getDescription(), changeLog, false, file, + serviceContext); + + DLAppServiceUtil.deleteFileEntry( + fileEntry.getFileEntryId()); + + return status; + } + catch (NoSuchFileEntryException nsfee) { + } + } + + DLAppServiceUtil.updateFileEntry( + fileEntry.getFileEntryId(), sourceFileName, + fileEntry.getMimeType(), title, description, changeLog, false, + file, serviceContext); + + if (fileEntry.getFolderId() != newParentFolderId) { + fileEntry = DLAppServiceUtil.moveFileEntry( + fileEntry.getFileEntryId(), newParentFolderId, + serviceContext); + } + + return status; + } + catch (PrincipalException pe) { + return HttpServletResponse.SC_FORBIDDEN; + } + catch (DuplicateFileException dfe) { + return HttpServletResponse.SC_PRECONDITION_FAILED; + } + catch (DuplicateFolderNameException dfne) { + return HttpServletResponse.SC_PRECONDITION_FAILED; + } + catch (LockException le) { + return WebDAVUtil.SC_LOCKED; + } + catch (Exception e) { + throw new WebDAVException(e); + } + finally { + FileUtil.delete(file); + } + } + + @Override + public int putResource(WebDAVRequest webDavRequest) throws WebDAVException { + File file = null; + + try { + HttpServletRequest request = webDavRequest.getHttpServletRequest(); + + String[] pathArray = webDavRequest.getPathArray(); + + long companyId = webDavRequest.getCompanyId(); + long groupId = webDavRequest.getGroupId(); + long parentFolderId = getParentFolderId(companyId, pathArray); + String title = WebDAVUtil.getResourceName(pathArray); + String description = StringPool.BLANK; + String changeLog = StringPool.BLANK; + + ServiceContext serviceContext = ServiceContextFactory.getInstance( + request); + + serviceContext.setAddGroupPermissions( + isAddGroupPermissions(groupId)); + serviceContext.setAddGuestPermissions(true); + + String contentType = GetterUtil.get( + request.getHeader(HttpHeaders.CONTENT_TYPE), + ContentTypes.APPLICATION_OCTET_STREAM); + + String extension = FileUtil.getExtension(title); + + file = FileUtil.createTempFile(extension); + + FileUtil.write(file, request.getInputStream()); + + if (contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) { + contentType = MimeTypesUtil.getContentType(file, title); + } + + try { + FileEntry fileEntry = DLAppServiceUtil.getFileEntry( + groupId, parentFolderId, title); + + if (!hasLock(fileEntry, webDavRequest.getLockUuid()) && + (fileEntry.getLock() != null)) { + + return WebDAVUtil.SC_LOCKED; + } + + long fileEntryId = fileEntry.getFileEntryId(); + + description = fileEntry.getDescription(); + + String[] assetTagNames = AssetTagLocalServiceUtil.getTagNames( + FileEntry.class.getName(), fileEntry.getFileEntryId()); + + serviceContext.setAssetTagNames(assetTagNames); + + DLAppServiceUtil.updateFileEntry( + fileEntryId, title, contentType, title, description, + changeLog, false, file, serviceContext); + } + catch (NoSuchFileEntryException nsfee) { + if (file.length() == 0) { + serviceContext.setWorkflowAction( + WorkflowConstants.ACTION_SAVE_DRAFT); + } + + DLAppServiceUtil.addFileEntry( + groupId, parentFolderId, title, contentType, title, + description, changeLog, file, serviceContext); + } + + if (_log.isInfoEnabled()) { + _log.info( + "Added " + StringUtil.merge(pathArray, StringPool.SLASH)); + } + + return HttpServletResponse.SC_CREATED; + } + catch (PrincipalException pe) { + return HttpServletResponse.SC_FORBIDDEN; + } + catch (NoSuchFolderException nsfe) { + return HttpServletResponse.SC_CONFLICT; + } + catch (PortalException pe) { + if (_log.isWarnEnabled()) { + _log.warn(pe, pe); + } + + return HttpServletResponse.SC_CONFLICT; + } + catch (Exception e) { + throw new WebDAVException(e); + } + finally { + FileUtil.delete(file); + } + } + + @Override + public Lock refreshResourceLock( + WebDAVRequest webDavRequest, String uuid, long timeout) + throws WebDAVException { + + Resource resource = getResource(webDavRequest); + + Lock lock = null; + + try { + if (resource instanceof DLFileEntryResourceImpl) { + lock = DLAppServiceUtil.refreshFileEntryLock(uuid, timeout); + } + else { + lock = DLAppServiceUtil.refreshFolderLock(uuid, timeout); + } + } + catch (Exception e) { + throw new WebDAVException(e); + } + + return lock; + } + + @Override + public boolean unlockResource(WebDAVRequest webDavRequest, String token) + throws WebDAVException { + + Resource resource = getResource(webDavRequest); + + try { + if (resource instanceof DLFileEntryResourceImpl) { + FileEntry fileEntry = (FileEntry)resource.getModel(); + + DLAppServiceUtil.unlockFileEntry( + fileEntry.getFileEntryId(), token); + + if (webDavRequest.isAppleDoubleRequest()) { + DLAppServiceUtil.deleteFileEntry( + fileEntry.getFileEntryId()); + } + } + else { + Folder folder = (Folder)resource.getModel(); + + DLAppServiceUtil.unlockFolder( + folder.getRepositoryId(), folder.getParentFolderId(), + folder.getName(), token); + } + + return true; + } + catch (Exception e) { + if (e instanceof InvalidLockException) { + if (_log.isWarnEnabled()) { + _log.warn(e.getMessage()); + } + } + else { + if (_log.isWarnEnabled()) { + _log.warn("Unable to unlock file entry", e); + } + } + } + + return false; + } + + protected boolean deleteResource( + long groupId, long parentFolderId, String name, String lockUuid) + throws Exception { + + try { + Folder folder = DLAppServiceUtil.getFolder( + groupId, parentFolderId, name); + + DLAppServiceUtil.deleteFolder(folder.getFolderId()); + + return true; + } + catch (NoSuchFolderException nsfe) { + try { + FileEntry fileEntry = DLAppServiceUtil.getFileEntry( + groupId, parentFolderId, name); + + if (!hasLock(fileEntry, lockUuid) && + (fileEntry.getLock() != null)) { + + throw new LockException(); + } + + DLAppServiceUtil.deleteFileEntryByTitle( + groupId, parentFolderId, name); + + return true; + } + catch (NoSuchFileEntryException nsfee) { + } + } + + return false; + } + + protected List getFileEntries( + WebDAVRequest webDavRequest, long parentFolderId) + throws Exception { + + List resources = new ArrayList(); + + List fileEntries = DLAppServiceUtil.getFileEntries( + webDavRequest.getGroupId(), parentFolderId); + + for (FileEntry fileEntry : fileEntries) { + Resource resource = toResource(webDavRequest, fileEntry, true); + + resources.add(resource); + } + + return resources; + } + + protected long getFolderId(long companyId, String[] pathArray) + throws Exception { + + return getFolderId(companyId, pathArray, false); + } + + protected long getFolderId( + long companyId, String[] pathArray, boolean parent) + throws Exception { + + long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID; + + if (pathArray.length <= 1) { + return folderId; + } + else { + long groupId = WebDAVUtil.getGroupId(companyId, pathArray); + + int x = pathArray.length; + + if (parent) { + x--; + } + + for (int i = 2; i < x; i++) { + String name = pathArray[i]; + + Folder folder = DLAppServiceUtil.getFolder( + groupId, folderId, name); + + if (groupId == folder.getRepositoryId()) { + folderId = folder.getFolderId(); + } + } + } + + return folderId; + } + + protected List getFolders( + WebDAVRequest webDavRequest, long parentFolderId) + throws Exception { + + List resources = new ArrayList(); + + long groupId = webDavRequest.getGroupId(); + + List folders = DLAppServiceUtil.getFolders( + groupId, parentFolderId, false); + + for (Folder folder : folders) { + Resource resource = toResource(webDavRequest, folder, true); + + resources.add(resource); + } + + return resources; + } + + protected long getParentFolderId(long companyId, String[] pathArray) + throws Exception { + + return getFolderId(companyId, pathArray, true); + } + + protected boolean hasLock(FileEntry fileEntry, String lockUuid) + throws Exception { + + if (Validator.isNull(lockUuid)) { + + // Client does not claim to know of a lock + + return fileEntry.hasLock(); + } + else { + + // Client claims to know of a lock. Verify the lock UUID. + + try { + return DLAppServiceUtil.verifyFileEntryLock( + fileEntry.getRepositoryId(), fileEntry.getFileEntryId(), + lockUuid); + } + catch (NoSuchLockException nsle) { + return false; + } + } + } + + protected Resource toResource( + WebDAVRequest webDavRequest, FileEntry fileEntry, boolean appendPath) { + + String parentPath = getRootPath() + webDavRequest.getPath(); + String name = StringPool.BLANK; + + if (appendPath) { + name = fileEntry.getTitle(); + } + + return new DLFileEntryResourceImpl( + webDavRequest, fileEntry, parentPath, name); + } + + protected Resource toResource( + WebDAVRequest webDavRequest, Folder folder, boolean appendPath) { + + String parentPath = getRootPath() + webDavRequest.getPath(); + String name = StringPool.BLANK; + + if (appendPath) { + name = folder.getName(); + } + + Resource resource = new BaseResourceImpl( + parentPath, name, folder.getName(), folder.getCreateDate(), + folder.getModifiedDate()); + + resource.setModel(folder); + resource.setClassName(Folder.class.getName()); + resource.setPrimaryKey(folder.getPrimaryKey()); + + return resource; + } + + private static Log _log = LogFactoryUtil.getLog(DLWebDAVStorageImpl.class); + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portlet/dynamicdatalists/action/EditRecordFileAction.java b/portal-impl/src/com/liferay/portlet/dynamicdatalists/action/EditRecordFileAction.java index 8a64ce23571cf4..ae98fc772ad1fe 100644 --- a/portal-impl/src/com/liferay/portlet/dynamicdatalists/action/EditRecordFileAction.java +++ b/portal-impl/src/com/liferay/portlet/dynamicdatalists/action/EditRecordFileAction.java @@ -53,9 +53,8 @@ public class EditRecordFileAction extends PortletAction { @Override public void processAction( - ActionMapping mapping, ActionForm form, - PortletConfig portletConfig, ActionRequest actionRequest, - ActionResponse actionResponse) + ActionMapping mapping, ActionForm form, PortletConfig portletConfig, + ActionRequest actionRequest, ActionResponse actionResponse) throws Exception { String cmd = ParamUtil.getString(actionRequest, Constants.CMD); diff --git a/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordLocalServiceImpl.java index e7fe4b0928e089..db5cf01718a420 100644 --- a/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordLocalServiceImpl.java @@ -112,8 +112,7 @@ public DDLRecord addRecord( updateAsset( userId, record, recordVersion, serviceContext.getAssetCategoryIds(), - serviceContext.getAssetTagNames(), - locale); + serviceContext.getAssetTagNames(), locale); // Workflow diff --git a/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordServiceImpl.java b/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordServiceImpl.java index fe5613a2a6d2c5..e3941be589c852 100644 --- a/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordServiceImpl.java @@ -34,8 +34,8 @@ public class DDLRecordServiceImpl extends DDLRecordServiceBaseImpl { public DDLRecord addRecord( - long groupId, long recordSetId, int displayIndex, - Fields fields, ServiceContext serviceContext) + long groupId, long recordSetId, int displayIndex, Fields fields, + ServiceContext serviceContext) throws PortalException, SystemException { DDLRecordSetPermission.check( diff --git a/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordSetServiceImpl.java b/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordSetServiceImpl.java index 058d1f1f94e5e8..20201c86a21686 100644 --- a/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordSetServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/impl/DDLRecordSetServiceImpl.java @@ -65,8 +65,7 @@ public DDLRecordSet getRecordSet(long recordSetId) } public DDLRecordSet updateMinDisplayRows( - long recordSetId, int minDisplayRows, - ServiceContext serviceContext) + long recordSetId, int minDisplayRows, ServiceContext serviceContext) throws PortalException, SystemException { DDLRecordSetPermission.check( diff --git a/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/persistence/DDLRecordSetFinderImpl.java b/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/persistence/DDLRecordSetFinderImpl.java index 18af4b563a2aa0..7cbb711fe92506 100644 --- a/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/persistence/DDLRecordSetFinderImpl.java +++ b/portal-impl/src/com/liferay/portlet/dynamicdatalists/service/persistence/DDLRecordSetFinderImpl.java @@ -96,8 +96,8 @@ public List findByKeywords( } return findByC_G_N_D_S( - companyId, groupId, names, descriptions, scope, andOperator, - start, end, orderByComparator); + companyId, groupId, names, descriptions, scope, andOperator, start, + end, orderByComparator); } public List findByC_G_N_D_S( diff --git a/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/CopyStructureAction.java b/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/CopyStructureAction.java index 7d2b10a7c55ebb..7152a57d297e7d 100644 --- a/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/CopyStructureAction.java +++ b/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/CopyStructureAction.java @@ -189,8 +189,7 @@ protected String getSaveAndContinueRedirect( portletURL.setParameter( "struts_action", "/dynamic_data_mapping/copy_structure"); portletURL.setParameter( - "structureId", String.valueOf(structure.getStructureId()), - false); + "structureId", String.valueOf(structure.getStructureId()), false); portletURL.setParameter( "copyDetailTemplates", ParamUtil.getString(actionRequest, "copyDetailTemplates"), false); diff --git a/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/EditStructureAction.java b/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/EditStructureAction.java index 664cbbcdd06f61..b6321b9262253a 100644 --- a/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/EditStructureAction.java +++ b/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/EditStructureAction.java @@ -85,8 +85,7 @@ else if (cmd.equals(Constants.DELETE)) { if (saveAndContinue) { redirect = getSaveAndContinueRedirect( - portletConfig, actionRequest, structure, - redirect); + portletConfig, actionRequest, structure, redirect); } } @@ -158,8 +157,7 @@ public ActionForward render( return mapping.findForward( getForward( - renderRequest, - "portlet.dynamic_data_mapping.edit_structure")); + renderRequest, "portlet.dynamic_data_mapping.edit_structure")); } protected void deleteStructure(ActionRequest actionRequest) diff --git a/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/EditTemplateAction.java b/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/EditTemplateAction.java index 66271a5d07c7fb..a49818e90b4eac 100644 --- a/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/EditTemplateAction.java +++ b/portal-impl/src/com/liferay/portlet/dynamicdatamapping/action/EditTemplateAction.java @@ -139,8 +139,7 @@ public ActionForward render( return mapping.findForward( getForward( - renderRequest, - "portlet.dynamic_data_mapping.edit_template")); + renderRequest, "portlet.dynamic_data_mapping.edit_template")); } protected void deleteTemplate(ActionRequest actionRequest) diff --git a/portal-impl/src/com/liferay/portlet/dynamicdatamapping/search/StructureSearch.java b/portal-impl/src/com/liferay/portlet/dynamicdatamapping/search/StructureSearch.java index 9958dd5b4fdc80..235b14a8c0849d 100644 --- a/portal-impl/src/com/liferay/portlet/dynamicdatamapping/search/StructureSearch.java +++ b/portal-impl/src/com/liferay/portlet/dynamicdatamapping/search/StructureSearch.java @@ -58,13 +58,11 @@ portletRequest, new StructureDisplayTerms(portletRequest), StructureDisplayTerms.CLASS_NAME_ID, String.valueOf(displayTerms.getClassNameId())); iteratorURL.setParameter( - StructureDisplayTerms.DESCRIPTION, - displayTerms.getDescription()); + StructureDisplayTerms.DESCRIPTION, displayTerms.getDescription()); iteratorURL.setParameter( StructureDisplayTerms.NAME, displayTerms.getName()); iteratorURL.setParameter( - StructureDisplayTerms.STORAGE_TYPE, - displayTerms.getStorageType()); + StructureDisplayTerms.STORAGE_TYPE, displayTerms.getStorageType()); } } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portlet/dynamicdatamapping/service/persistence/DDMStructureFinderImpl.java b/portal-impl/src/com/liferay/portlet/dynamicdatamapping/service/persistence/DDMStructureFinderImpl.java index b305979db5f5b1..74035ba0ac423b 100644 --- a/portal-impl/src/com/liferay/portlet/dynamicdatamapping/service/persistence/DDMStructureFinderImpl.java +++ b/portal-impl/src/com/liferay/portlet/dynamicdatamapping/service/persistence/DDMStructureFinderImpl.java @@ -292,8 +292,7 @@ protected int doCountByC_G_C_N_D_S_T( sql = CustomSQLUtil.replaceKeywords( sql, "lower(name)", StringPool.LIKE, false, names); sql = CustomSQLUtil.replaceKeywords( - sql, "description", StringPool.LIKE, false, - descriptions); + sql, "description", StringPool.LIKE, false, descriptions); sql = CustomSQLUtil.replaceKeywords( sql, "storageType", StringPool.LIKE, true, storageTypes); sql = CustomSQLUtil.replaceAndOperator(sql, andOperator); @@ -373,8 +372,7 @@ protected List doFindByC_G_C_N_D_S_T( sql = CustomSQLUtil.replaceKeywords( sql, "lower(name)", StringPool.LIKE, false, names); sql = CustomSQLUtil.replaceKeywords( - sql, "description", StringPool.LIKE, false, - descriptions); + sql, "description", StringPool.LIKE, false, descriptions); sql = CustomSQLUtil.replaceKeywords( sql, "storageType", StringPool.LIKE, true, storageTypes); sql = CustomSQLUtil.replaceAndOperator(sql, andOperator); diff --git a/portal-impl/src/com/liferay/portlet/expando/model/impl/ExpandoBridgeImpl.java b/portal-impl/src/com/liferay/portlet/expando/model/impl/ExpandoBridgeImpl.java index 04da972032f456..f07455f5ae556a 100644 --- a/portal-impl/src/com/liferay/portlet/expando/model/impl/ExpandoBridgeImpl.java +++ b/portal-impl/src/com/liferay/portlet/expando/model/impl/ExpandoBridgeImpl.java @@ -493,14 +493,14 @@ public void setAttributes( if (secure) { ExpandoValueServiceUtil.addValues( _companyId, _className, - ExpandoTableConstants.DEFAULT_TABLE_NAME, - _classPK, attributes); + ExpandoTableConstants.DEFAULT_TABLE_NAME, _classPK, + attributes); } else { ExpandoValueLocalServiceUtil.addValues( _companyId, _className, - ExpandoTableConstants.DEFAULT_TABLE_NAME, - _classPK, attributes); + ExpandoTableConstants.DEFAULT_TABLE_NAME, _classPK, + attributes); } } catch (Exception e) { diff --git a/portal-impl/src/com/liferay/portlet/expando/service/impl/ExpandoValueLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/expando/service/impl/ExpandoValueLocalServiceImpl.java index 3f8963c0b4a8b6..e356feefbf43d1 100644 --- a/portal-impl/src/com/liferay/portlet/expando/service/impl/ExpandoValueLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/expando/service/impl/ExpandoValueLocalServiceImpl.java @@ -1225,8 +1225,8 @@ public Map getData( value.setData(column.getDefaultData()); Serializable attributeValue = doGetData( - companyId, className, tableName, column.getName(), - classPK, value, column.getType()); + companyId, className, tableName, column.getName(), classPK, + value, column.getType()); attributeValues.put(column.getName(), attributeValue); } @@ -1938,8 +1938,8 @@ public ExpandoValue getValue( } protected ExpandoValue doAddValue( - long companyId, long classNameId, long tableId, - long columnId, long classPK, String data) + long companyId, long classNameId, long tableId, long columnId, + long classPK, String data) throws SystemException { ExpandoRow row = expandoRowPersistence.fetchByT_C(tableId, classPK); diff --git a/portal-impl/src/com/liferay/portlet/expando/service/impl/ExpandoValueServiceImpl.java b/portal-impl/src/com/liferay/portlet/expando/service/impl/ExpandoValueServiceImpl.java index 97661f8bf866e8..8197b5c623371b 100644 --- a/portal-impl/src/com/liferay/portlet/expando/service/impl/ExpandoValueServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/expando/service/impl/ExpandoValueServiceImpl.java @@ -67,8 +67,8 @@ public ExpandoValue addValue( } public void addValues( - long companyId, String className, String tableName, - long classPK, Map attributeValues) + long companyId, String className, String tableName, long classPK, + Map attributeValues) throws PortalException, SystemException { for (Map.Entry entry : diff --git a/portal-impl/src/com/liferay/portlet/flags/messaging/FlagsRequestMessageListener.java b/portal-impl/src/com/liferay/portlet/flags/messaging/FlagsRequestMessageListener.java index 03515de217ba6e..71871dd19a64ba 100644 --- a/portal-impl/src/com/liferay/portlet/flags/messaging/FlagsRequestMessageListener.java +++ b/portal-impl/src/com/liferay/portlet/flags/messaging/FlagsRequestMessageListener.java @@ -154,8 +154,8 @@ protected void doReceive(Message message) throws Exception { company, groupName, reporterEmailAddress, reporterUserName, reportedEmailAddress, reportedUserName, reportedURL, flagsRequest.getClassPK(), flagsRequest.getContentTitle(), - contentType, flagsRequest.getContentURL(), reason, - fromName, fromAddress, recipient.getFullName(), + contentType, flagsRequest.getContentURL(), reason, fromName, + fromAddress, recipient.getFullName(), recipient.getEmailAddress(), subject, body, serviceContext); } catch (IOException ioe) { diff --git a/portal-impl/src/com/liferay/portlet/invitation/action/ViewAction.java b/portal-impl/src/com/liferay/portlet/invitation/action/ViewAction.java index 420147cc0a0b1f..bba1b6326ca169 100644 --- a/portal-impl/src/com/liferay/portlet/invitation/action/ViewAction.java +++ b/portal-impl/src/com/liferay/portlet/invitation/action/ViewAction.java @@ -118,31 +118,21 @@ else if (Validator.isNotNull(emailAddress)) { subject = StringUtil.replace( subject, new String[] { - "[$FROM_ADDRESS$]", - "[$FROM_NAME$]", - "[$PAGE_URL$]", + "[$FROM_ADDRESS$]", "[$FROM_NAME$]", "[$PAGE_URL$]", "[$PORTAL_URL$]" }, new String[] { - fromAddress, - fromName, - layoutFullURL, - portalURL + fromAddress, fromName, layoutFullURL, portalURL }); body = StringUtil.replace( body, new String[] { - "[$FROM_ADDRESS$]", - "[$FROM_NAME$]", - "[$PAGE_URL$]", + "[$FROM_ADDRESS$]", "[$FROM_NAME$]", "[$PAGE_URL$]", "[$PORTAL_URL$]" }, new String[] { - fromAddress, - fromName, - layoutFullURL, - portalURL + fromAddress, fromName, layoutFullURL, portalURL }); for (String emailAddress : validEmailAddresses) { diff --git a/portal-impl/src/com/liferay/portlet/journal/action/RSSAction.java b/portal-impl/src/com/liferay/portlet/journal/action/RSSAction.java index feee27a7ce8e0d..e6dbe16382cbb1 100644 --- a/portal-impl/src/com/liferay/portlet/journal/action/RSSAction.java +++ b/portal-impl/src/com/liferay/portlet/journal/action/RSSAction.java @@ -345,13 +345,10 @@ protected String processURL( url = StringUtil.replace( url, new String[] { - "@group_id@", - "@image_path@", - "@main_path@" + "@group_id@", "@image_path@", "@main_path@" }, new String[] { - String.valueOf(feed.getGroupId()), - themeDisplay.getPathImage(), + String.valueOf(feed.getGroupId()), themeDisplay.getPathImage(), themeDisplay.getPathMain() } ); diff --git a/portal-impl/src/com/liferay/portlet/journal/lar/JournalPortletDataHandlerImpl.java b/portal-impl/src/com/liferay/portlet/journal/lar/JournalPortletDataHandlerImpl.java index 36eda9b0b59431..1e2ce54436f132 100644 --- a/portal-impl/src/com/liferay/portlet/journal/lar/JournalPortletDataHandlerImpl.java +++ b/portal-impl/src/com/liferay/portlet/journal/lar/JournalPortletDataHandlerImpl.java @@ -805,8 +805,7 @@ public static void importFeed( feed.setTargetLayoutFriendlyUrl( StringUtil.replace( feed.getTargetLayoutFriendlyUrl(), - "@data_handler_group_friendly_url@", - newGroupFriendlyURL)); + "@data_handler_group_friendly_url@", newGroupFriendlyURL)); } String feedId = feed.getFeedId(); diff --git a/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalArticleLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalArticleLocalServiceImpl.java index 52f5e0d0f3b8d1..d186f31f41be87 100644 --- a/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalArticleLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalArticleLocalServiceImpl.java @@ -1,3434 +1,3433 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portlet.journal.service.impl; - -import com.liferay.portal.NoSuchImageException; -import com.liferay.portal.kernel.dao.orm.QueryUtil; -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.sanitizer.SanitizerUtil; -import com.liferay.portal.kernel.search.Field; -import com.liferay.portal.kernel.search.Hits; -import com.liferay.portal.kernel.search.Indexer; -import com.liferay.portal.kernel.search.IndexerRegistryUtil; -import com.liferay.portal.kernel.search.QueryConfig; -import com.liferay.portal.kernel.search.SearchContext; -import com.liferay.portal.kernel.search.Sort; -import com.liferay.portal.kernel.util.CalendarFactoryUtil; -import com.liferay.portal.kernel.util.CharPool; -import com.liferay.portal.kernel.util.ContentTypes; -import com.liferay.portal.kernel.util.DateUtil; -import com.liferay.portal.kernel.util.FileUtil; -import com.liferay.portal.kernel.util.GetterUtil; -import com.liferay.portal.kernel.util.HtmlUtil; -import com.liferay.portal.kernel.util.HttpUtil; -import com.liferay.portal.kernel.util.ListUtil; -import com.liferay.portal.kernel.util.LocaleUtil; -import com.liferay.portal.kernel.util.LocalizationUtil; -import com.liferay.portal.kernel.util.MathUtil; -import com.liferay.portal.kernel.util.OrderByComparator; -import com.liferay.portal.kernel.util.PropsKeys; -import com.liferay.portal.kernel.util.StringPool; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.kernel.util.Time; -import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.kernel.workflow.WorkflowConstants; -import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil; -import com.liferay.portal.kernel.xml.Document; -import com.liferay.portal.kernel.xml.DocumentException; -import com.liferay.portal.kernel.xml.Element; -import com.liferay.portal.kernel.xml.Node; -import com.liferay.portal.kernel.xml.SAXReaderUtil; -import com.liferay.portal.kernel.xml.XPath; -import com.liferay.portal.model.Company; -import com.liferay.portal.model.Group; -import com.liferay.portal.model.Image; -import com.liferay.portal.model.ModelHintsUtil; -import com.liferay.portal.model.ResourceConstants; -import com.liferay.portal.model.User; -import com.liferay.portal.service.ServiceContext; -import com.liferay.portal.service.ServiceContextUtil; -import com.liferay.portal.servlet.filters.cache.CacheUtil; -import com.liferay.portal.theme.ThemeDisplay; -import com.liferay.portal.util.PortalUtil; -import com.liferay.portal.util.PortletKeys; -import com.liferay.portal.util.PrefsPropsUtil; -import com.liferay.portal.util.PropsValues; -import com.liferay.portal.util.SubscriptionSender; -import com.liferay.portal.webserver.WebServerServletTokenUtil; -import com.liferay.portlet.asset.NoSuchEntryException; -import com.liferay.portlet.asset.model.AssetEntry; -import com.liferay.portlet.asset.model.AssetLink; -import com.liferay.portlet.asset.model.AssetLinkConstants; -import com.liferay.portlet.dynamicdatamapping.util.DDMXMLUtil; -import com.liferay.portlet.expando.model.ExpandoBridge; -import com.liferay.portlet.journal.ArticleContentException; -import com.liferay.portlet.journal.ArticleDisplayDateException; -import com.liferay.portlet.journal.ArticleExpirationDateException; -import com.liferay.portlet.journal.ArticleIdException; -import com.liferay.portlet.journal.ArticleReviewDateException; -import com.liferay.portlet.journal.ArticleSmallImageNameException; -import com.liferay.portlet.journal.ArticleSmallImageSizeException; -import com.liferay.portlet.journal.ArticleTitleException; -import com.liferay.portlet.journal.ArticleTypeException; -import com.liferay.portlet.journal.ArticleVersionException; -import com.liferay.portlet.journal.DuplicateArticleIdException; -import com.liferay.portlet.journal.NoSuchArticleException; -import com.liferay.portlet.journal.NoSuchArticleResourceException; -import com.liferay.portlet.journal.NoSuchStructureException; -import com.liferay.portlet.journal.NoSuchTemplateException; -import com.liferay.portlet.journal.StructureXsdException; -import com.liferay.portlet.journal.model.JournalArticle; -import com.liferay.portlet.journal.model.JournalArticleConstants; -import com.liferay.portlet.journal.model.JournalArticleDisplay; -import com.liferay.portlet.journal.model.JournalArticleResource; -import com.liferay.portlet.journal.model.JournalStructure; -import com.liferay.portlet.journal.model.JournalTemplate; -import com.liferay.portlet.journal.model.impl.JournalArticleDisplayImpl; -import com.liferay.portlet.journal.service.base.JournalArticleLocalServiceBaseImpl; -import com.liferay.portlet.journal.util.JournalUtil; -import com.liferay.portlet.journal.util.comparator.ArticleIDComparator; -import com.liferay.portlet.journal.util.comparator.ArticleVersionComparator; -import com.liferay.portlet.journalcontent.util.JournalContentUtil; - -import java.io.File; -import java.io.IOException; -import java.io.Serializable; - -import java.util.Calendar; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import javax.portlet.PortletPreferences; - -/** - * @author Brian Wing Shun Chan - * @author Raymond Augé - * @author Bruno Farache - * @author Juan Fernández - */ -public class JournalArticleLocalServiceImpl - extends JournalArticleLocalServiceBaseImpl { - - public JournalArticle addArticle( - long userId, long groupId, long classNameId, long classPK, - String articleId, boolean autoArticleId, double version, - Map titleMap, Map descriptionMap, - String content, String type, String structureId, String templateId, - String layoutUuid, int displayDateMonth, int displayDateDay, - int displayDateYear, int displayDateHour, int displayDateMinute, - int expirationDateMonth, int expirationDateDay, - int expirationDateYear, int expirationDateHour, - int expirationDateMinute, boolean neverExpire, int reviewDateMonth, - int reviewDateDay, int reviewDateYear, int reviewDateHour, - int reviewDateMinute, boolean neverReview, boolean indexable, - boolean smallImage, String smallImageURL, File smallImageFile, - Map images, String articleURL, - ServiceContext serviceContext) - throws PortalException, SystemException { - - // Article - - User user = userPersistence.findByPrimaryKey(userId); - articleId = articleId.trim().toUpperCase(); - - Date displayDate = PortalUtil.getDate( - displayDateMonth, displayDateDay, displayDateYear, - displayDateHour, displayDateMinute, user.getTimeZone(), - new ArticleDisplayDateException()); - - Date expirationDate = null; - - if (!neverExpire) { - expirationDate = PortalUtil.getDate( - expirationDateMonth, expirationDateDay, expirationDateYear, - expirationDateHour, expirationDateMinute, user.getTimeZone(), - new ArticleExpirationDateException()); - } - - Date reviewDate = null; - - if (!neverReview) { - reviewDate = PortalUtil.getDate( - reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour, - reviewDateMinute, user.getTimeZone(), - new ArticleReviewDateException()); - } - - byte[] smallImageBytes = null; - - try { - smallImageBytes = FileUtil.getBytes(smallImageFile); - } - catch (IOException ioe) { - } - - Date now = new Date(); - - validate( - user.getCompanyId(), groupId, classNameId, articleId, autoArticleId, - version, titleMap, content, type, structureId, templateId, - smallImage, smallImageURL, smallImageFile, smallImageBytes); - - if (autoArticleId) { - articleId = String.valueOf(counterLocalService.increment()); - } - - long id = counterLocalService.increment(); - - long resourcePrimKey = - journalArticleResourceLocalService.getArticleResourcePrimKey( - serviceContext.getUuid(), groupId, articleId); - - JournalArticle article = journalArticlePersistence.create(id); - - Locale locale = LocaleUtil.getDefault(); - - String defaultLanguageId = GetterUtil.getString( - serviceContext.getAttribute("defaultLanguageId")); - - if (Validator.isNotNull(defaultLanguageId)) { - locale = LocaleUtil.fromLanguageId(defaultLanguageId); - } - - String title = titleMap.get(locale); - - content = format( - user, groupId, articleId, version, false, content, structureId, - images); - - article.setResourcePrimKey(resourcePrimKey); - article.setGroupId(groupId); - article.setCompanyId(user.getCompanyId()); - article.setUserId(user.getUserId()); - article.setUserName(user.getFullName()); - article.setCreateDate(serviceContext.getCreateDate(now)); - article.setModifiedDate(serviceContext.getModifiedDate(now)); - article.setClassNameId(classNameId); - article.setClassPK(classPK); - article.setArticleId(articleId); - article.setVersion(version); - article.setTitleMap(titleMap, locale); - article.setUrlTitle(getUniqueUrlTitle(id, groupId, articleId, title)); - article.setDescriptionMap(descriptionMap, locale); - article.setContent(content); - article.setType(type); - article.setStructureId(structureId); - article.setTemplateId(templateId); - article.setLayoutUuid(layoutUuid); - article.setDisplayDate(displayDate); - article.setExpirationDate(expirationDate); - article.setReviewDate(reviewDate); - article.setIndexable(indexable); - article.setSmallImage(smallImage); - article.setSmallImageId(counterLocalService.increment()); - article.setSmallImageURL(smallImageURL); - - if ((expirationDate == null) || expirationDate.after(now)) { - article.setStatus(WorkflowConstants.STATUS_DRAFT); - } - else { - article.setStatus(WorkflowConstants.STATUS_EXPIRED); - } - - journalArticlePersistence.update(article, false); - - // Resources - - if (serviceContext.isAddGroupPermissions() || - serviceContext.isAddGuestPermissions()) { - - addArticleResources( - article, serviceContext.isAddGroupPermissions(), - serviceContext.isAddGuestPermissions()); - } - else { - addArticleResources( - article, serviceContext.getGroupPermissions(), - serviceContext.getGuestPermissions()); - } - - // Expando - - ExpandoBridge expandoBridge = article.getExpandoBridge(); - - expandoBridge.setAttributes(serviceContext); - - // Small image - - saveImages( - smallImage, article.getSmallImageId(), smallImageFile, - smallImageBytes); - - // Asset - - updateAsset( - userId, article, serviceContext.getAssetCategoryIds(), - serviceContext.getAssetTagNames(), - serviceContext.getAssetLinkEntryIds()); - - // Message boards - - if (PropsValues.JOURNAL_ARTICLE_COMMENTS_ENABLED) { - mbMessageLocalService.addDiscussionMessage( - userId, article.getUserName(), groupId, - JournalArticle.class.getName(), resourcePrimKey, - WorkflowConstants.ACTION_PUBLISH); - } - - // Email - - PortletPreferences preferences = - ServiceContextUtil.getPortletPreferences(serviceContext); - - sendEmail( - article, articleURL, preferences, "requested", serviceContext); - - // Workflow - - if (classNameId == 0) { - WorkflowHandlerRegistryUtil.startWorkflowInstance( - user.getCompanyId(), groupId, userId, - JournalArticle.class.getName(), article.getId(), article, - serviceContext); - - if (serviceContext.getWorkflowAction() != - WorkflowConstants.ACTION_PUBLISH) { - - // Indexer - - Indexer indexer = IndexerRegistryUtil.getIndexer( - JournalArticle.class); - - indexer.reindex(article); - } - } - else { - updateStatus( - userId, article, WorkflowConstants.STATUS_APPROVED, null, - serviceContext); - } - - return article; - } - - public void addArticleResources( - JournalArticle article, boolean addGroupPermissions, - boolean addGuestPermissions) - throws PortalException, SystemException { - - resourceLocalService.addResources( - article.getCompanyId(), article.getGroupId(), - article.getUserId(), JournalArticle.class.getName(), - article.getResourcePrimKey(), false, addGroupPermissions, - addGuestPermissions); - } - - public void addArticleResources( - JournalArticle article, String[] groupPermissions, - String[] guestPermissions) - throws PortalException, SystemException { - - resourceLocalService.addModelResources( - article.getCompanyId(), article.getGroupId(), - article.getUserId(), JournalArticle.class.getName(), - article.getResourcePrimKey(), groupPermissions, guestPermissions); - } - - public void addArticleResources( - long groupId, String articleId, boolean addGroupPermissions, - boolean addGuestPermissions) - throws PortalException, SystemException { - - JournalArticle article = getLatestArticle(groupId, articleId); - - addArticleResources(article, addGroupPermissions, addGuestPermissions); - } - - public void addArticleResources( - long groupId, String articleId, String[] groupPermissions, - String[] guestPermissions) - throws PortalException, SystemException { - - JournalArticle article = getLatestArticle(groupId, articleId); - - addArticleResources(article, groupPermissions, guestPermissions); - } - - public JournalArticle checkArticleResourcePrimKey( - long groupId, String articleId, double version) - throws PortalException, SystemException { - - JournalArticle article = journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - - if (article.getResourcePrimKey() > 0) { - return article; - } - - long resourcePrimKey = - journalArticleResourceLocalService.getArticleResourcePrimKey( - groupId, articleId); - - article.setResourcePrimKey(resourcePrimKey); - - journalArticlePersistence.update(article, false); - - return article; - } - - public void checkArticles() throws PortalException, SystemException { - Date now = new Date(); - - List articles = - journalArticleFinder.findByExpirationDate( - 0, WorkflowConstants.STATUS_APPROVED, now); - - if (_log.isDebugEnabled()) { - _log.debug("Expiring " + articles.size() + " articles"); - } - - Set companyIds = new HashSet(); - - for (JournalArticle article : articles) { - article.setStatus(WorkflowConstants.STATUS_EXPIRED); - - journalArticlePersistence.update(article, false); - - if (article.isIndexable()) { - Indexer indexer = IndexerRegistryUtil.getIndexer( - JournalArticle.class); - - indexer.delete(article); - } - - updatePreviousApprovedArticle(article); - - JournalContentUtil.clearCache( - article.getGroupId(), article.getArticleId(), - article.getTemplateId()); - - companyIds.add(article.getCompanyId()); - } - - for (long companyId : companyIds) { - CacheUtil.clearCache(companyId); - } - - articles = journalArticleFinder.findByReviewDate( - 0, now, new Date(now.getTime() - _JOURNAL_ARTICLE_CHECK_INTERVAL)); - - if (_log.isDebugEnabled()) { - _log.debug( - "Sending review notifications for " + articles.size() + - " articles"); - } - - for (JournalArticle article : articles) { - String articleURL = StringPool.BLANK; - - long ownerId = article.getGroupId(); - int ownerType = PortletKeys.PREFS_OWNER_TYPE_GROUP; - long plid = PortletKeys.PREFS_PLID_SHARED; - String portletId = PortletKeys.JOURNAL; - - PortletPreferences preferences = - portletPreferencesLocalService.getPreferences( - article.getCompanyId(), ownerId, ownerType, plid, - portletId); - - sendEmail( - article, articleURL, preferences, "review", - new ServiceContext()); - } - } - - public void checkNewLine(long groupId, String articleId, double version) - throws PortalException, SystemException { - - JournalArticle article = journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - - String content = GetterUtil.getString(article.getContent()); - - if (content.indexOf("\\n") != -1) { - content = StringUtil.replace( - content, - new String[] {"\\n", "\\r"}, - new String[] {"\n", "\r"}); - - article.setContent(content); - - journalArticlePersistence.update(article, false); - } - } - - public void checkStructure(long groupId, String articleId, double version) - throws PortalException, SystemException { - - JournalArticle article = journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - - if (Validator.isNull(article.getStructureId())) { - return; - } - - try { - checkStructure(article); - } - catch (DocumentException de) { - _log.error(de, de); - } - } - - public JournalArticle copyArticle( - long userId, long groupId, String oldArticleId, String newArticleId, - boolean autoArticleId, double version) - throws PortalException, SystemException { - - // Article - - User user = userPersistence.findByPrimaryKey(userId); - oldArticleId = oldArticleId.trim().toUpperCase(); - newArticleId = newArticleId.trim().toUpperCase(); - Date now = new Date(); - - JournalArticle oldArticle = journalArticlePersistence.findByG_A_V( - groupId, oldArticleId, version); - - if (autoArticleId) { - newArticleId = String.valueOf(counterLocalService.increment()); - } - else { - validate(groupId, newArticleId); - } - - long id = counterLocalService.increment(); - - long resourcePrimKey = - journalArticleResourceLocalService.getArticleResourcePrimKey( - groupId, newArticleId); - - JournalArticle newArticle = journalArticlePersistence.create(id); - - newArticle.setResourcePrimKey(resourcePrimKey); - newArticle.setGroupId(groupId); - newArticle.setCompanyId(user.getCompanyId()); - newArticle.setUserId(user.getUserId()); - newArticle.setUserName(user.getFullName()); - newArticle.setCreateDate(now); - newArticle.setModifiedDate(now); - newArticle.setArticleId(newArticleId); - newArticle.setVersion(JournalArticleConstants.VERSION_DEFAULT); - newArticle.setTitle(oldArticle.getTitle()); - newArticle.setDescription(oldArticle.getDescription()); - - try { - copyArticleImages(oldArticle, newArticle); - } - catch (Exception e) { - newArticle.setContent(oldArticle.getContent()); - } - - newArticle.setType(oldArticle.getType()); - newArticle.setStructureId(oldArticle.getStructureId()); - newArticle.setTemplateId(oldArticle.getTemplateId()); - newArticle.setLayoutUuid(oldArticle.getLayoutUuid()); - newArticle.setDisplayDate(oldArticle.getDisplayDate()); - newArticle.setExpirationDate(oldArticle.getExpirationDate()); - newArticle.setReviewDate(oldArticle.getReviewDate()); - newArticle.setIndexable(oldArticle.isIndexable()); - newArticle.setSmallImage(oldArticle.isSmallImage()); - newArticle.setSmallImageId(counterLocalService.increment()); - newArticle.setSmallImageURL(oldArticle.getSmallImageURL()); - newArticle.setStatus(oldArticle.getStatus()); - - journalArticlePersistence.update(newArticle, false); - - // Resources - - addArticleResources(newArticle, true, true); - - // Small image - - if (oldArticle.getSmallImage()) { - Image image = imageLocalService.getImage( - oldArticle.getSmallImageId()); - - byte[] smallImageBytes = image.getTextObj(); - - imageLocalService.updateImage( - newArticle.getSmallImageId(), smallImageBytes); - } - - // Asset - - long[] assetCategoryIds = assetCategoryLocalService.getCategoryIds( - JournalArticle.class.getName(), oldArticle.getResourcePrimKey()); - String[] assetTagNames = assetTagLocalService.getTagNames( - JournalArticle.class.getName(), oldArticle.getResourcePrimKey()); - - updateAsset(userId, newArticle, assetCategoryIds, assetTagNames, null); - - return newArticle; - } - - public void deleteArticle( - JournalArticle article, String articleURL, - ServiceContext serviceContext) - throws PortalException, SystemException { - - if (article.isApproved() && - isLatestVersion( - article.getGroupId(), article.getArticleId(), - article.getVersion(), WorkflowConstants.STATUS_APPROVED)) { - - updatePreviousApprovedArticle(article); - } - - // Email - - PortletPreferences preferences = - ServiceContextUtil.getPortletPreferences(serviceContext); - - if ((preferences != null) && !article.isApproved() && - isLatestVersion( - article.getGroupId(), article.getArticleId(), - article.getVersion())) { - - sendEmail( - article, articleURL, preferences, "denied", serviceContext); - } - - // Images - - journalArticleImageLocalService.deleteImages( - article.getGroupId(), article.getArticleId(), article.getVersion()); - - // Workflow - - if (!article.isDraft()) { - workflowInstanceLinkLocalService.deleteWorkflowInstanceLink( - article.getCompanyId(), article.getGroupId(), - JournalArticle.class.getName(), article.getId()); - } - - int articlesCount = journalArticlePersistence.countByG_A( - article.getGroupId(), article.getArticleId()); - - if (articlesCount == 1) { - - // Ratings - - ratingsStatsLocalService.deleteStats( - JournalArticle.class.getName(), article.getResourcePrimKey()); - - // Message boards - - mbMessageLocalService.deleteDiscussionMessages( - JournalArticle.class.getName(), article.getResourcePrimKey()); - - // Asset - - assetEntryLocalService.deleteEntry( - JournalArticle.class.getName(), article.getResourcePrimKey()); - - // Content searches - - journalContentSearchLocalService.deleteArticleContentSearches( - article.getGroupId(), article.getArticleId()); - - // Small image - - imageLocalService.deleteImage(article.getSmallImageId()); - - // Expando - - expandoValueLocalService.deleteValues( - JournalArticle.class.getName(), article.getResourcePrimKey()); - - // Resources - - resourceLocalService.deleteResource( - article.getCompanyId(), JournalArticle.class.getName(), - ResourceConstants.SCOPE_INDIVIDUAL, - article.getResourcePrimKey()); - - // Resource - - try { - journalArticleResourceLocalService.deleteArticleResource( - article.getGroupId(), article.getArticleId()); - } - catch (NoSuchArticleResourceException nsare) { - } - } - - // Article - - journalArticlePersistence.remove(article); - } - - public void deleteArticle( - long groupId, String articleId, double version, String articleURL, - ServiceContext serviceContext) - throws PortalException, SystemException { - - JournalArticle article = journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - - deleteArticle(article, articleURL, serviceContext); - } - - public void deleteArticle( - long groupId, String articleId, ServiceContext serviceContext) - throws PortalException, SystemException { - - List articles = journalArticlePersistence.findByG_A( - groupId, articleId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, - new ArticleVersionComparator(true)); - - for (JournalArticle article : articles) { - deleteArticle(article, null, serviceContext); - } - } - - public void deleteArticles(long groupId) - throws PortalException, SystemException { - - for (JournalArticle article : - journalArticlePersistence.findByGroupId(groupId)) { - - deleteArticle(article, null, null); - } - } - - public void deleteLayoutArticleReferences(long groupId, String layoutUuid) - throws SystemException { - - List articles = journalArticlePersistence.findByG_L( - groupId, layoutUuid); - - for (JournalArticle article: articles) { - article.setLayoutUuid(StringPool.BLANK); - - journalArticlePersistence.update(article, false); - } - } - - public JournalArticle expireArticle( - long userId, long groupId, String articleId, double version, - String articleURL, ServiceContext serviceContext) - throws PortalException, SystemException { - - return updateStatus( - userId, groupId, articleId, version, - WorkflowConstants.STATUS_EXPIRED, articleURL, serviceContext); - } - - public void expireArticle( - long userId, long groupId, String articleId, String articleURL, - ServiceContext serviceContext) - throws PortalException, SystemException { - - List articles = journalArticlePersistence.findByG_A( - groupId, articleId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, - new ArticleVersionComparator(true)); - - for (JournalArticle article : articles) { - expireArticle( - userId, groupId, article.getArticleId(), article.getVersion(), - articleURL, serviceContext); - } - } - - public JournalArticle getArticle(long id) - throws PortalException, SystemException { - - return journalArticlePersistence.findByPrimaryKey(id); - } - - public JournalArticle getArticle(long groupId, String articleId) - throws PortalException, SystemException { - - // Get the latest article that is approved, if none are approved, get - // the latest unapproved article - - try { - return getLatestArticle( - groupId, articleId, WorkflowConstants.STATUS_APPROVED); - } - catch (NoSuchArticleException nsae) { - return getLatestArticle( - groupId, articleId, WorkflowConstants.STATUS_ANY); - } - } - - public JournalArticle getArticle( - long groupId, String articleId, double version) - throws PortalException, SystemException { - - return journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - } - - public JournalArticle getArticle( - long groupId, String className, long classPK) - throws PortalException, SystemException { - - long classNameId = PortalUtil.getClassNameId(className); - - List articles = journalArticlePersistence.findByG_C_C( - groupId, classNameId, classPK); - - if (articles.isEmpty()) { - throw new NoSuchArticleException( - "No approved JournalArticle exists with the key {groupId=" - + groupId + ", className=" + className + ", classPK=" + - classPK + "}"); - } - - return articles.get(0); - } - - public JournalArticle getArticleByUrlTitle(long groupId, String urlTitle) - throws PortalException, SystemException { - - // Get the latest article that is approved, if none are approved, get - // the latest unapproved article - - try { - return getLatestArticleByUrlTitle( - groupId, urlTitle, WorkflowConstants.STATUS_APPROVED); - } - catch (NoSuchArticleException nsae) { - return getLatestArticleByUrlTitle( - groupId, urlTitle, WorkflowConstants.STATUS_PENDING); - } - } - - public String getArticleContent( - JournalArticle article, String templateId, String viewMode, - String languageId, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - JournalArticleDisplay articleDisplay = getArticleDisplay( - article, templateId, viewMode, languageId, 1, null, themeDisplay); - - if (articleDisplay == null) { - return StringPool.BLANK; - } - else { - return articleDisplay.getContent(); - } - } - - public String getArticleContent( - long groupId, String articleId, double version, String viewMode, - String templateId, String languageId, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - JournalArticleDisplay articleDisplay = getArticleDisplay( - groupId, articleId, version, templateId, viewMode, languageId, - themeDisplay); - - if (articleDisplay == null) { - return StringPool.BLANK; - } - else { - return articleDisplay.getContent(); - } - } - - public String getArticleContent( - long groupId, String articleId, double version, String viewMode, - String languageId, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getArticleContent( - groupId, articleId, version, viewMode, null, languageId, - themeDisplay); - } - - public String getArticleContent( - long groupId, String articleId, String viewMode, String templateId, - String languageId, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - JournalArticleDisplay articleDisplay = getArticleDisplay( - groupId, articleId, templateId, viewMode, languageId, themeDisplay); - - return articleDisplay.getContent(); - } - - public String getArticleContent( - long groupId, String articleId, String viewMode, String languageId, - ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getArticleContent( - groupId, articleId, viewMode, null, languageId, themeDisplay); - } - - public JournalArticleDisplay getArticleDisplay( - JournalArticle article, String templateId, String viewMode, - String languageId, int page, String xmlRequest, - ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - String content = null; - - if (page < 1) { - page = 1; - } - - int numberOfPages = 1; - boolean paginate = false; - boolean pageFlow = false; - - boolean cacheable = true; - - if (Validator.isNull(xmlRequest)) { - xmlRequest = ""; - } - - Map tokens = JournalUtil.getTokens( - article.getGroupId(), themeDisplay, xmlRequest); - - tokens.put( - "article_resource_pk", - String.valueOf(article.getResourcePrimKey())); - - String defaultTemplateId = article.getTemplateId(); - - if (article.isTemplateDriven()) { - if (Validator.isNull(templateId)) { - templateId = defaultTemplateId; - } - - tokens.put("structure_id", article.getStructureId()); - tokens.put("template_id", templateId); - } - - String xml = article.getContent(); - - try { - Document document = null; - - Element rootElement = null; - - if (article.isTemplateDriven()) { - document = SAXReaderUtil.read(xml); - - rootElement = document.getRootElement(); - - Document requestDocument = SAXReaderUtil.read(xmlRequest); - - List pages = rootElement.elements("page"); - - if (!pages.isEmpty()) { - pageFlow = true; - - String targetPage = requestDocument.valueOf( - "/request/parameters/parameter[name='targetPage']/" + - "value"); - - Element pageElement = null; - - if (Validator.isNotNull(targetPage)) { - XPath xPathSelector = SAXReaderUtil.createXPath( - "/root/page[@id = '" + targetPage + "']"); - - pageElement = (Element)xPathSelector.selectSingleNode( - document); - } - - if (pageElement != null) { - document = SAXReaderUtil.createDocument(pageElement); - - rootElement = document.getRootElement(); - - numberOfPages = pages.size(); - } - else { - if (page > pages.size()) { - page = 1; - } - - pageElement = pages.get(page - 1); - - document = SAXReaderUtil.createDocument(pageElement); - - rootElement = document.getRootElement(); - - numberOfPages = pages.size(); - paginate = true; - } - } - - rootElement.add(requestDocument.getRootElement().createCopy()); - - JournalUtil.addAllReservedEls( - rootElement, tokens, article, languageId); - - xml = DDMXMLUtil.formatXML(document); - } - } - catch (DocumentException de) { - throw new SystemException(de); - } - catch (IOException ioe) { - throw new SystemException(ioe); - } - - try { - if (_log.isDebugEnabled()) { - _log.debug( - "Transforming " + article.getArticleId() + " " + - article.getVersion() + " " + languageId); - } - - String script = null; - String langType = null; - - if (article.isTemplateDriven()) { - - // Try with specified template first (in the current group and - // the global group). If a template is not specified, use the - // default one. If the specified template does not exit, use the - // default one. If the default one does not exist, throw an - // exception. - - JournalTemplate template = null; - - try { - template = journalTemplatePersistence.findByG_T( - article.getGroupId(), templateId); - } - catch (NoSuchTemplateException nste1) { - try { - Group companyGroup = groupLocalService.getCompanyGroup( - article.getCompanyId()); - - template = journalTemplatePersistence.findByG_T( - companyGroup.getGroupId(), templateId); - - tokens.put( - "company_group_id", - String.valueOf(companyGroup.getGroupId())); - } - catch (NoSuchTemplateException nste2) { - if (!defaultTemplateId.equals(templateId)) { - template = journalTemplatePersistence.findByG_T( - article.getGroupId(), defaultTemplateId); - } - else { - throw nste1; - } - } - } - - script = template.getXsl(); - langType = template.getLangType(); - cacheable = template.isCacheable(); - } - - content = JournalUtil.transform( - themeDisplay, tokens, viewMode, languageId, xml, script, - langType); - - if (!pageFlow) { - String[] pieces = StringUtil.split( - content, PropsValues.JOURNAL_ARTICLE_TOKEN_PAGE_BREAK); - - if (pieces.length > 1) { - if (page > pieces.length) { - page = 1; - } - - content = pieces[page - 1]; - numberOfPages = pieces.length; - paginate = true; - } - } - } - catch (Exception e) { - throw new SystemException(e); - } - - return new JournalArticleDisplayImpl( - article.getCompanyId(), article.getId(), - article.getResourcePrimKey(), article.getGroupId(), - article.getUserId(), article.getArticleId(), article.getVersion(), - article.getTitle(languageId), article.getUrlTitle(), - article.getDescription(languageId), article.getAvailableLocales(), - content, article.getType(), article.getStructureId(), templateId, - article.isSmallImage(), article.getSmallImageId(), - article.getSmallImageURL(), numberOfPages, page, paginate, - cacheable); - } - - public JournalArticleDisplay getArticleDisplay( - long groupId, String articleId, double version, String templateId, - String viewMode, String languageId, int page, String xmlRequest, - ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - Date now = new Date(); - - JournalArticle article = journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - - if (article.isExpired()) { - Date expirationDate = article.getExpirationDate(); - - if ((expirationDate != null) && expirationDate.before(now)) { - return null; - } - } - - if (article.getDisplayDate().after(now)) { - return null; - } - - return getArticleDisplay( - article, templateId, viewMode, languageId, page, xmlRequest, - themeDisplay); - } - - public JournalArticleDisplay getArticleDisplay( - long groupId, String articleId, double version, String templateId, - String viewMode, String languageId, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getArticleDisplay( - groupId, articleId, version, templateId, viewMode, languageId, 1, - null, themeDisplay); - } - - public JournalArticleDisplay getArticleDisplay( - long groupId, String articleId, String viewMode, String languageId, - int page, String xmlRequest, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getArticleDisplay( - groupId, articleId, null, viewMode, languageId, page, xmlRequest, - themeDisplay); - } - - public JournalArticleDisplay getArticleDisplay( - long groupId, String articleId, String templateId, String viewMode, - String languageId, int page, String xmlRequest, - ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - JournalArticle article = getDisplayArticle(groupId, articleId); - - return getArticleDisplay( - groupId, articleId, article.getVersion(), templateId, viewMode, - languageId, page, xmlRequest, themeDisplay); - } - - public JournalArticleDisplay getArticleDisplay( - long groupId, String articleId, String templateId, String viewMode, - String languageId, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - JournalArticle article = getDisplayArticle(groupId, articleId); - - return getArticleDisplay( - groupId, articleId, article.getVersion(), templateId, viewMode, - languageId, themeDisplay); - } - - public JournalArticleDisplay getArticleDisplay( - long groupId, String articleId, String viewMode, String languageId, - ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - return getArticleDisplay( - groupId, articleId, null, viewMode, languageId, themeDisplay); - } - - public List getArticles() throws SystemException { - return journalArticlePersistence.findAll(); - } - - public List getArticles(long groupId) - throws SystemException { - - return journalArticlePersistence.findByGroupId(groupId); - } - - public List getArticles(long groupId, int start, int end) - throws SystemException { - - return journalArticlePersistence.findByGroupId(groupId, start, end); - } - - public List getArticles( - long groupId, int start, int end, OrderByComparator obc) - throws SystemException { - - return journalArticlePersistence.findByGroupId( - groupId, start, end, obc); - } - - public List getArticles(long groupId, String articleId) - throws SystemException { - - return journalArticlePersistence.findByG_A(groupId, articleId); - } - - public List getArticlesBySmallImageId(long smallImageId) - throws SystemException { - - return journalArticlePersistence.findBySmallImageId(smallImageId); - } - - public int getArticlesCount(long groupId) throws SystemException { - return journalArticlePersistence.countByGroupId(groupId); - } - - public List getCompanyArticles( - long companyId, double version, int status, int start, int end) - throws SystemException { - - if (status == WorkflowConstants.STATUS_ANY) { - return journalArticlePersistence.findByC_V( - companyId, version, start, end, new ArticleIDComparator(true)); - } - else { - return journalArticlePersistence.findByC_V_ST( - companyId, version, status, start, end, - new ArticleIDComparator(true)); - } - } - - public List getCompanyArticles( - long companyId, int status, int start, int end) - throws SystemException { - - if (status == WorkflowConstants.STATUS_ANY) { - return journalArticlePersistence.findByCompanyId( - companyId, start, end, new ArticleIDComparator(true)); - } - else { - return journalArticlePersistence.findByC_ST( - companyId, status, start, end, new ArticleIDComparator(true)); - } - } - - public int getCompanyArticlesCount( - long companyId, double version, int status, int start, int end) - throws SystemException { - - if (status == WorkflowConstants.STATUS_ANY) { - return journalArticlePersistence.countByC_V(companyId, version); - } - else { - return journalArticlePersistence.countByC_V_ST( - companyId, version, status); - } - } - - public int getCompanyArticlesCount(long companyId, int status) - throws SystemException { - - if (status == WorkflowConstants.STATUS_ANY) { - return journalArticlePersistence.countByCompanyId(companyId); - } - else { - return journalArticlePersistence.countByC_ST(companyId, status); - } - } - - public JournalArticle getDisplayArticle(long groupId, String articleId) - throws PortalException, SystemException { - - List articles = journalArticlePersistence.findByG_A_ST( - groupId, articleId, WorkflowConstants.STATUS_APPROVED); - - if (articles.isEmpty()) { - throw new NoSuchArticleException( - "No approved JournalArticle exists with the key {groupId=" + - groupId + ", " + "articleId=" + articleId + "}"); - - } - - Date now = new Date(); - - for (int i = 0; i < articles.size(); i++) { - JournalArticle article = articles.get(i); - - Date expirationDate = article.getExpirationDate(); - - if (article.getDisplayDate().before(now) && - ((expirationDate == null) || expirationDate.after(now))) { - - return article; - } - } - - return articles.get(0); - } - - public JournalArticle getDisplayArticleByUrlTitle( - long groupId, String urlTitle) - throws PortalException, SystemException { - - List articles = null; - - OrderByComparator orderByComparator = new ArticleVersionComparator(); - - articles = journalArticlePersistence.findByG_UT_ST( - groupId, urlTitle, WorkflowConstants.STATUS_APPROVED, - QueryUtil.ALL_POS, QueryUtil.ALL_POS, orderByComparator); - - if (articles.isEmpty()) { - throw new NoSuchArticleException( - "No JournalArticle exists with the key {groupId=" + groupId + - ", urlTitle=" + urlTitle + "}"); - } - - Date now = new Date(); - - for (JournalArticle article : articles) { - Date expirationDate = article.getExpirationDate(); - - if (article.getDisplayDate().before(now) && - ((expirationDate == null) || expirationDate.after(now))) { - - return article; - } - } - - return articles.get(0); - } - - public JournalArticle getLatestArticle(long resourcePrimKey) - throws PortalException, SystemException { - - return getLatestArticle(resourcePrimKey, WorkflowConstants.STATUS_ANY); - } - - public JournalArticle getLatestArticle(long resourcePrimKey, int status) - throws PortalException, SystemException { - - return getLatestArticle(resourcePrimKey, status, true); - } - - public JournalArticle getLatestArticle( - long resourcePrimKey, int status, boolean preferApproved) - throws PortalException, SystemException { - - List articles = null; - - OrderByComparator orderByComparator = new ArticleVersionComparator(); - - if (status == WorkflowConstants.STATUS_ANY) { - if (preferApproved) { - articles = journalArticlePersistence.findByR_ST( - resourcePrimKey, WorkflowConstants.STATUS_APPROVED, 0, 1, - orderByComparator); - } - - if ((articles == null) || (articles.size() == 0)) { - articles = journalArticlePersistence.findByResourcePrimKey( - resourcePrimKey, 0, 1, orderByComparator); - } - } - else { - articles = journalArticlePersistence.findByR_ST( - resourcePrimKey, status, 0, 1, orderByComparator); - } - - if (articles.isEmpty()) { - throw new NoSuchArticleException( - "No JournalArticle exists with the key {resourcePrimKey=" + - resourcePrimKey + "}"); - } - - return articles.get(0); - } - - public JournalArticle getLatestArticle(long groupId, String articleId) - throws PortalException, SystemException { - - return getLatestArticle( - groupId, articleId, WorkflowConstants.STATUS_ANY); - } - - public JournalArticle getLatestArticle( - long groupId, String articleId, int status) - throws PortalException, SystemException { - - List articles = null; - - OrderByComparator orderByComparator = new ArticleVersionComparator(); - - if (status == WorkflowConstants.STATUS_ANY) { - articles = journalArticlePersistence.findByG_A( - groupId, articleId, 0, 1, orderByComparator); - } - else { - articles = journalArticlePersistence.findByG_A_ST( - groupId, articleId, status, 0, 1, orderByComparator); - } - - if (articles.isEmpty()) { - throw new NoSuchArticleException( - "No JournalArticle exists with the key {groupId=" + groupId + - ", articleId=" + articleId + ", status=" + status + "}"); - } - - return articles.get(0); - } - - public JournalArticle getLatestArticle( - long groupId, String className, long classPK) - throws PortalException, SystemException { - - long classNameId = PortalUtil.getClassNameId(className); - - List articles = journalArticlePersistence.findByG_C_C( - groupId, classNameId, classPK, 0, 1, - new ArticleVersionComparator()); - - if (articles.isEmpty()) { - throw new NoSuchArticleException( - "No JournalArticle exists with the key {groupId=" + groupId + - ", className=" + className + ", classPK =" + classPK + "}"); - } - - return articles.get(0); - } - - public JournalArticle getLatestArticleByUrlTitle( - long groupId, String urlTitle, int status) - throws PortalException, SystemException { - - List articles = null; - - OrderByComparator orderByComparator = new ArticleVersionComparator(); - - if (status == WorkflowConstants.STATUS_ANY) { - articles = journalArticlePersistence.findByG_UT( - groupId, urlTitle, 0, 1, orderByComparator); - } - else { - articles = journalArticlePersistence.findByG_UT_ST( - groupId, urlTitle, status, 0, 1, orderByComparator); - } - - if (articles.isEmpty()) { - throw new NoSuchArticleException( - "No JournalArticle exists with the key {groupId=" + groupId + - ", urlTitle=" + urlTitle + ", status=" + status + "}"); - } - - return articles.get(0); - } - - public double getLatestVersion(long groupId, String articleId) - throws PortalException, SystemException { - - JournalArticle article = getLatestArticle(groupId, articleId); - - return article.getVersion(); - } - - public double getLatestVersion(long groupId, String articleId, int status) - throws PortalException, SystemException { - - JournalArticle article = getLatestArticle(groupId, articleId, status); - - return article.getVersion(); - } - - public List getStructureArticles( - long groupId, String structureId) - throws SystemException { - - return journalArticlePersistence.findByG_S(groupId, structureId); - } - - public List getStructureArticles( - long groupId, String structureId, int start, int end, - OrderByComparator obc) - throws SystemException { - - return journalArticlePersistence.findByG_S( - groupId, structureId, start, end, obc); - } - - public int getStructureArticlesCount(long groupId, String structureId) - throws SystemException { - - return journalArticlePersistence.countByG_S(groupId, structureId); - } - - public List getTemplateArticles( - long groupId, String templateId) - throws SystemException { - - return journalArticlePersistence.findByG_T(groupId, templateId); - } - - public List getTemplateArticles( - long groupId, String templateId, int start, int end, - OrderByComparator obc) - throws SystemException { - - return journalArticlePersistence.findByG_T( - groupId, templateId, start, end, obc); - } - - public int getTemplateArticlesCount(long groupId, String templateId) - throws SystemException { - - return journalArticlePersistence.countByG_T(groupId, templateId); - } - - public boolean hasArticle(long groupId, String articleId) - throws SystemException { - - try { - getArticle(groupId, articleId); - - return true; - } - catch (PortalException pe) { - return false; - } - } - - public boolean isLatestVersion( - long groupId, String articleId, double version) - throws PortalException, SystemException { - - if (getLatestVersion(groupId, articleId) == version) { - return true; - } - else { - return false; - } - } - - public boolean isLatestVersion( - long groupId, String articleId, double version, int status) - throws PortalException, SystemException { - - if (getLatestVersion(groupId, articleId, status) == version) { - return true; - } - else { - return false; - } - } - - public JournalArticle removeArticleLocale( - long groupId, String articleId, double version, String languageId) - throws PortalException, SystemException { - - JournalArticle article = journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - - String title = article.getTitle(); - - title = LocalizationUtil.removeLocalization( - title, "static-content", languageId, true); - - article.setTitle(title); - - String description = article.getDescription(); - - description = LocalizationUtil.removeLocalization( - description, "static-content", languageId, true); - - article.setDescription(description); - - String content = article.getContent(); - - if (article.isTemplateDriven()) { - content = JournalUtil.removeArticleLocale(content, languageId); - } - else { - content = LocalizationUtil.removeLocalization( - content, "static-content", languageId, true); - } - - article.setContent(content); - - journalArticlePersistence.update(article, false); - - return article; - } - - public List search( - long companyId, long groupId, long classNameId, String keywords, - Double version, String type, String structureId, String templateId, - Date displayDateGT, Date displayDateLT, int status, Date reviewDate, - int start, int end, OrderByComparator obc) - throws SystemException { - - return journalArticleFinder.findByKeywords( - companyId, groupId, classNameId, keywords, version, type, - structureId, templateId, displayDateGT, displayDateLT, status, - reviewDate, start, end, obc); - } - - public List search( - long companyId, long groupId, long classNameId, String articleId, - Double version, String title, String description, String content, - String type, String structureId, String templateId, - Date displayDateGT, Date displayDateLT, int status, Date reviewDate, - boolean andOperator, int start, int end, OrderByComparator obc) - throws SystemException { - - return journalArticleFinder.findByC_G_C_A_V_T_D_C_T_S_T_D_S_R( - companyId, groupId, classNameId, articleId, version, title, - description, content, type, structureId, templateId, displayDateGT, - displayDateLT, status, reviewDate, andOperator, start, end, obc); - } - - public List search( - long companyId, long groupId, long classNameId, String articleId, - Double version, String title, String description, String content, - String type, String[] structureIds, String[] templateIds, - Date displayDateGT, Date displayDateLT, int status, Date reviewDate, - boolean andOperator, int start, int end, OrderByComparator obc) - throws SystemException { - - return journalArticleFinder.findByC_G_C_A_V_T_D_C_T_S_T_D_S_R( - companyId, groupId, classNameId, articleId, version, title, - description, content, type, structureIds, templateIds, - displayDateGT, displayDateLT, status, reviewDate, andOperator, - start, end, obc); - } - - public Hits search( - long companyId, long groupId, long classNameId, String structureId, - String templateId, String keywords, - LinkedHashMap params, int start, int end, Sort sort) - throws SystemException { - - String articleId = null; - String title = null; - String description = null; - String content = null; - boolean andOperator = false; - - if (Validator.isNotNull(keywords)) { - articleId = keywords; - title = keywords; - description = keywords; - content = keywords; - } - else { - andOperator = true; - } - - String status = String.valueOf(WorkflowConstants.STATUS_ANY); - - params.put("keywords", keywords); - - return search( - companyId, groupId, classNameId, articleId, title, description, - content, null, status, structureId, templateId, params, andOperator, - start, end, sort); - } - - public Hits search( - long companyId, long groupId, long classNameId, String articleId, - String title, String description, String content, String type, - String status, String structureId, String templateId, - LinkedHashMap params, boolean andSearch, int start, - int end, Sort sort) - throws SystemException { - - try { - SearchContext searchContext = new SearchContext(); - - searchContext.setAndSearch(andSearch); - - Map attributes = - new HashMap(); - - attributes.put(Field.CLASS_NAME_ID, classNameId); - attributes.put(Field.CONTENT, content); - attributes.put(Field.DESCRIPTION, description); - attributes.put(Field.STATUS, status); - attributes.put(Field.TITLE, title); - attributes.put(Field.TYPE, type); - attributes.put("articleId", articleId); - attributes.put("params", params); - attributes.put("structureId", structureId); - attributes.put("templateId", templateId); - - searchContext.setAttributes(attributes); - - searchContext.setCompanyId(companyId); - searchContext.setGroupIds(new long[] {groupId}); - searchContext.setEnd(end); - - String keywords = (String)params.remove("keywords"); - - if (Validator.isNotNull(keywords)) { - searchContext.setKeywords(keywords); - } - - QueryConfig queryConfig = new QueryConfig(); - - queryConfig.setHighlightEnabled(false); - queryConfig.setScoreEnabled(false); - - searchContext.setQueryConfig(queryConfig); - - searchContext.setSorts(new Sort[] {sort}); - searchContext.setStart(start); - - Indexer indexer = IndexerRegistryUtil.getIndexer( - JournalArticle.class); - - return indexer.search(searchContext); - } - catch (Exception e) { - throw new SystemException(e); - } - } - - public int searchCount( - long companyId, long groupId, long classNameId, String keywords, - Double version, String type, String structureId, String templateId, - Date displayDateGT, Date displayDateLT, int status, Date reviewDate) - throws SystemException { - - return journalArticleFinder.countByKeywords( - companyId, groupId, classNameId, keywords, version, type, - structureId, templateId, displayDateGT, displayDateLT, status, - reviewDate); - } - - public int searchCount( - long companyId, long groupId, long classNameId, String articleId, - Double version, String title, String description, String content, - String type, String structureId, String templateId, - Date displayDateGT, Date displayDateLT, int status, Date reviewDate, - boolean andOperator) - throws SystemException { - - return journalArticleFinder.countByC_G_C_A_V_T_D_C_T_S_T_D_S_R( - companyId, groupId, classNameId, articleId, version, title, - description, content, type, structureId, templateId, displayDateGT, - displayDateLT, status, reviewDate, andOperator); - } - - public int searchCount( - long companyId, long groupId, long classNameId, String articleId, - Double version, String title, String description, String content, - String type, String[] structureIds, String[] templateIds, - Date displayDateGT, Date displayDateLT, int status, Date reviewDate, - boolean andOperator) - throws SystemException { - - return journalArticleFinder.countByC_G_C_A_V_T_D_C_T_S_T_D_S_R( - companyId, groupId, classNameId, articleId, version, title, - description, content, type, structureIds, templateIds, - displayDateGT, displayDateLT, status, reviewDate, andOperator); - } - - public void subscribe(long userId, long groupId) - throws PortalException, SystemException { - - subscriptionLocalService.addSubscription( - userId, groupId, JournalArticle.class.getName(), groupId); - } - - public void unsubscribe(long userId, long groupId) - throws PortalException, SystemException { - - subscriptionLocalService.deleteSubscription( - userId, JournalArticle.class.getName(), groupId); - } - - public JournalArticle updateArticle( - long userId, long groupId, String articleId, double version, - Map titleMap, Map descriptionMap, - String content, String layoutUuid, ServiceContext serviceContext) - throws PortalException, SystemException { - - User user = userPersistence.findByPrimaryKey(userId); - - JournalArticle article = journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - - Date displayDate = article.getDisplayDate(); - - int displayDateMonth = 0; - int displayDateDay = 0; - int displayDateYear = 0; - int displayDateHour = 0; - int displayDateMinute = 0; - - if (displayDate != null) { - Calendar displayCal = CalendarFactoryUtil.getCalendar( - user.getTimeZone()); - - displayCal.setTime(displayDate); - - displayDateMonth = displayCal.get(Calendar.MONTH); - displayDateDay = displayCal.get(Calendar.DATE); - displayDateYear = displayCal.get(Calendar.YEAR); - displayDateHour = displayCal.get(Calendar.HOUR); - displayDateMinute = displayCal.get(Calendar.MINUTE); - - if (displayCal.get(Calendar.AM_PM) == Calendar.PM) { - displayDateHour += 12; - } - } - - Date expirationDate = article.getExpirationDate(); - - int expirationDateMonth = 0; - int expirationDateDay = 0; - int expirationDateYear = 0; - int expirationDateHour = 0; - int expirationDateMinute = 0; - boolean neverExpire = true; - - if (expirationDate != null) { - Calendar expirationCal = CalendarFactoryUtil.getCalendar( - user.getTimeZone()); - - expirationCal.setTime(expirationDate); - - expirationDateMonth = expirationCal.get(Calendar.MONTH); - expirationDateDay = expirationCal.get(Calendar.DATE); - expirationDateYear = expirationCal.get(Calendar.YEAR); - expirationDateHour = expirationCal.get(Calendar.HOUR); - expirationDateMinute = expirationCal.get(Calendar.MINUTE); - neverExpire = false; - - if (expirationCal.get(Calendar.AM_PM) == Calendar.PM) { - expirationDateHour += 12; - } - } - - Date reviewDate = article.getReviewDate(); - - int reviewDateMonth = 0; - int reviewDateDay = 0; - int reviewDateYear = 0; - int reviewDateHour = 0; - int reviewDateMinute = 0; - boolean neverReview = true; - - if (reviewDate != null) { - Calendar reviewCal = CalendarFactoryUtil.getCalendar( - user.getTimeZone()); - - reviewCal.setTime(reviewDate); - - reviewDateMonth = reviewCal.get(Calendar.MONTH); - reviewDateDay = reviewCal.get(Calendar.DATE); - reviewDateYear = reviewCal.get(Calendar.YEAR); - reviewDateHour = reviewCal.get(Calendar.HOUR); - reviewDateMinute = reviewCal.get(Calendar.MINUTE); - neverReview = false; - - if (reviewCal.get(Calendar.AM_PM) == Calendar.PM) { - reviewDateHour += 12; - } - } - - return updateArticle( - userId, groupId, articleId, version, titleMap, descriptionMap, - content, article.getType(), article.getStructureId(), - article.getTemplateId(), layoutUuid, displayDateMonth, - displayDateDay, displayDateYear, displayDateHour, displayDateMinute, - expirationDateMonth, expirationDateDay, expirationDateYear, - expirationDateHour, expirationDateMinute, neverExpire, - reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour, - reviewDateMinute, neverReview, article.getIndexable(), - article.isSmallImage(), article.getSmallImageURL(), null, null, - null, serviceContext); - } - - public JournalArticle updateArticle( - long userId, long groupId, String articleId, double version, - Map titleMap, Map descriptionMap, - String content, String type, String structureId, String templateId, - String layoutUuid, int displayDateMonth, int displayDateDay, - int displayDateYear, int displayDateHour, int displayDateMinute, - int expirationDateMonth, int expirationDateDay, - int expirationDateYear, int expirationDateHour, - int expirationDateMinute, boolean neverExpire, int reviewDateMonth, - int reviewDateDay, int reviewDateYear, int reviewDateHour, - int reviewDateMinute, boolean neverReview, boolean indexable, - boolean smallImage, String smallImageURL, File smallImageFile, - Map images, String articleURL, - ServiceContext serviceContext) - throws PortalException, SystemException { - - // Article - - User user = userPersistence.findByPrimaryKey(userId); - articleId = articleId.trim().toUpperCase(); - - Date displayDate = PortalUtil.getDate( - displayDateMonth, displayDateDay, displayDateYear, - displayDateHour, displayDateMinute, user.getTimeZone(), - new ArticleDisplayDateException()); - - Date expirationDate = null; - - if (!neverExpire) { - expirationDate = PortalUtil.getDate( - expirationDateMonth, expirationDateDay, expirationDateYear, - expirationDateHour, expirationDateMinute, user.getTimeZone(), - new ArticleExpirationDateException()); - } - - Date now = new Date(); - - boolean expired = false; - - if ((expirationDate != null) && expirationDate.before(now)) { - expired = true; - } - - Date reviewDate = null; - - if (!neverReview) { - reviewDate = PortalUtil.getDate( - reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour, - reviewDateMinute, user.getTimeZone(), - new ArticleReviewDateException()); - } - - byte[] smallImageBytes = null; - - try { - smallImageBytes = FileUtil.getBytes(smallImageFile); - } - catch (IOException ioe) { - } - - JournalArticle oldArticle = null; - double oldVersion = 0; - - boolean incrementVersion = false; - - boolean imported = GetterUtil.getBoolean( - serviceContext.getAttribute("imported")); - - if (imported) { - oldArticle = getArticle(groupId, articleId, version); - oldVersion = version; - - if (expired) { - return expireArticle( - userId, groupId, articleId, version, articleURL, - serviceContext); - } - } - else { - oldArticle = getLatestArticle( - groupId, articleId, WorkflowConstants.STATUS_ANY); - - oldVersion = oldArticle.getVersion(); - - if ((version > 0) && (version != oldVersion)) { - throw new ArticleVersionException(); - } - - if (DateUtil.compareTo( - oldArticle.getModifiedDate(), serviceContext.getFormDate()) - > 0) { - - throw new ArticleVersionException(); - } - - if (oldArticle.isApproved() || oldArticle.isExpired()) { - incrementVersion = true; - } - } - - validate( - user.getCompanyId(), groupId, oldArticle.getClassNameId(), titleMap, - content, type, structureId, templateId, smallImage, smallImageURL, - smallImageFile, smallImageBytes); - - JournalArticle article = null; - - if (incrementVersion) { - double newVersion = MathUtil.format(oldVersion + 0.1, 1, 1); - - long id = counterLocalService.increment(); - - article = journalArticlePersistence.create(id); - - article.setResourcePrimKey(oldArticle.getResourcePrimKey()); - article.setGroupId(oldArticle.getGroupId()); - article.setCompanyId(oldArticle.getCompanyId()); - article.setUserId(user.getUserId()); - article.setUserName(user.getFullName()); - article.setCreateDate(serviceContext.getModifiedDate(now)); - article.setClassNameId(oldArticle.getClassNameId()); - article.setClassPK(oldArticle.getClassPK()); - article.setArticleId(articleId); - article.setVersion(newVersion); - article.setSmallImageId(oldArticle.getSmallImageId()); - } - else { - article = oldArticle; - } - - Locale locale = LocaleUtil.getDefault(); - - String defaultLanguageId = GetterUtil.getString( - serviceContext.getAttribute("defaultLanguageId")); - - if (Validator.isNotNull(defaultLanguageId)) { - locale = LocaleUtil.fromLanguageId(defaultLanguageId); - } - - String title = titleMap.get(locale); - - content = format( - user, groupId, articleId, article.getVersion(), incrementVersion, - content, structureId, images); - - article.setModifiedDate(serviceContext.getModifiedDate(now)); - article.setTitleMap(titleMap, locale); - article.setUrlTitle( - getUniqueUrlTitle(article.getId(), groupId, articleId, title)); - article.setDescriptionMap(descriptionMap, locale); - article.setContent(content); - article.setType(type); - article.setStructureId(structureId); - article.setTemplateId(templateId); - article.setLayoutUuid(layoutUuid); - article.setDisplayDate(displayDate); - article.setExpirationDate(expirationDate); - article.setReviewDate(reviewDate); - article.setIndexable(indexable); - article.setSmallImage(smallImage); - - if (article.getSmallImageId() == 0) { - article.setSmallImageId(counterLocalService.increment()); - } - - article.setSmallImageURL(smallImageURL); - - if (oldArticle.isPending()) { - article.setStatus(oldArticle.getStatus()); - } - else if (!expired) { - article.setStatus(WorkflowConstants.STATUS_DRAFT); - } - else { - article.setStatus(WorkflowConstants.STATUS_EXPIRED); - } - - journalArticlePersistence.update(article, false); - - // Asset - - updateAsset( - userId, article, serviceContext.getAssetCategoryIds(), - serviceContext.getAssetTagNames(), - serviceContext.getAssetLinkEntryIds()); - - // Expando - - ExpandoBridge expandoBridge = article.getExpandoBridge(); - - expandoBridge.setAttributes(serviceContext); - - // Small image - - saveImages( - smallImage, article.getSmallImageId(), smallImageFile, - smallImageBytes); - - // Email - - PortletPreferences preferences = - ServiceContextUtil.getPortletPreferences(serviceContext); - - // Workflow - - if (serviceContext.getWorkflowAction() == - WorkflowConstants.ACTION_PUBLISH) { - - sendEmail( - article, articleURL, preferences, "requested", serviceContext); - - WorkflowHandlerRegistryUtil.startWorkflowInstance( - user.getCompanyId(), groupId, userId, - JournalArticle.class.getName(), article.getId(), - article, serviceContext); - } - else if (article.getVersion() == - JournalArticleConstants.VERSION_DEFAULT) { - - // Indexer - - Indexer indexer = IndexerRegistryUtil.getIndexer( - JournalArticle.class); - - indexer.reindex(article); - } - - return article; - } - - public JournalArticle updateArticle( - long userId, long groupId, String articleId, double version, - String content, ServiceContext serviceContext) - throws PortalException, SystemException { - - JournalArticle article = journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - - return updateArticle( - userId, groupId, articleId, version, article.getTitleMap(), - article.getDescriptionMap(), content, article.getLayoutUuid(), - serviceContext); - } - - /** - * @deprecated {@link #updateArticleTranslation(long, String, double, - * Locale, String, String, String, Map, ServiceContext)} - */ - public JournalArticle updateArticleTranslation( - long groupId, String articleId, double version, Locale locale, - String title, String description, String content, - Map images) - throws PortalException, SystemException { - - return updateArticleTranslation( - groupId, articleId, version, locale, title, description, content, - images, null); - } - - public JournalArticle updateArticleTranslation( - long groupId, String articleId, double version, Locale locale, - String title, String description, String content, - Map images, ServiceContext serviceContext) - throws PortalException, SystemException { - - validateContent(content); - - JournalArticle oldArticle = getLatestArticle( - groupId, articleId, WorkflowConstants.STATUS_ANY); - - double oldVersion = oldArticle.getVersion(); - - if ((version > 0) && (version != oldVersion)) { - throw new ArticleVersionException(); - } - - if (serviceContext != null) { - if (DateUtil.compareTo( - oldArticle.getModifiedDate(), serviceContext.getFormDate()) - > 0) { - - throw new ArticleVersionException(); - } - } - - JournalArticle article = null; - - User user = userService.getUserById(oldArticle.getUserId()); - - if (!oldArticle.isDraft()) { - double newVersion = MathUtil.format(oldVersion + 0.1, 1, 1); - - long id = counterLocalService.increment(); - - article = journalArticlePersistence.create(id); - - article.setResourcePrimKey(oldArticle.getResourcePrimKey()); - article.setGroupId(oldArticle.getGroupId()); - article.setCompanyId(oldArticle.getCompanyId()); - article.setUserId(oldArticle.getUserId()); - article.setUserName(user.getFullName()); - article.setCreateDate(new Date()); - article.setModifiedDate(new Date()); - article.setClassNameId(oldArticle.getClassNameId()); - article.setClassPK(oldArticle.getClassPK()); - article.setArticleId(articleId); - article.setVersion(newVersion); - article.setTitleMap(oldArticle.getTitleMap()); - article.setUrlTitle( - getUniqueUrlTitle(article.getId(), groupId, articleId, title)); - article.setDescriptionMap(oldArticle.getDescriptionMap()); - article.setType(oldArticle.getType()); - article.setStructureId(oldArticle.getStructureId()); - article.setTemplateId(oldArticle.getTemplateId()); - article.setLayoutUuid(oldArticle.getLayoutUuid()); - article.setDisplayDate(oldArticle.getDisplayDate()); - article.setExpirationDate(oldArticle.getExpirationDate()); - article.setReviewDate(oldArticle.getReviewDate()); - article.setIndexable(oldArticle.getIndexable()); - article.setSmallImage(oldArticle.getSmallImage()); - article.setSmallImageId(oldArticle.getSmallImageId()); - - if (article.getSmallImageId() == 0) { - article.setSmallImageId(counterLocalService.increment()); - } - - article.setSmallImageURL(oldArticle.getSmallImageURL()); - - article.setStatus(WorkflowConstants.STATUS_DRAFT); - article.setStatusDate(new Date()); - } - else { - article = oldArticle; - } - - Map titleMap = article.getTitleMap(); - - titleMap.put(locale, title); - - article.setTitleMap(titleMap); - - Map descriptionMap = article.getDescriptionMap(); - - descriptionMap.put(locale, description); - - article.setDescriptionMap(descriptionMap); - - content = format( - user, groupId, articleId, version, !oldArticle.isDraft(), content, - oldArticle.getStructureId(), images); - - article.setContent(content); - - journalArticlePersistence.update(article, false); - - return article; - } - - public void updateAsset( - long userId, JournalArticle article, long[] assetCategoryIds, - String[] assetTagNames, long[] assetLinkEntryIds) - throws PortalException, SystemException { - - // Get the earliest display date and latest expiration date among - // all article versions - - Date[] dateInterval = getDateInterval( - article.getGroupId(), article.getArticleId(), - article.getDisplayDate(), article.getExpirationDate()); - - Date displayDate = dateInterval[0]; - Date expirationDate = dateInterval[1]; - - boolean visible = article.isApproved(); - - if (article.getClassNameId() > 0) { - visible = false; - } - - boolean addDraftAssetEntry = false; - - if (!article.isApproved() && - (article.getVersion() != JournalArticleConstants.VERSION_DEFAULT)) { - - int approvedArticlesCount = journalArticlePersistence.countByG_A_ST( - article.getGroupId(), article.getArticleId(), - JournalArticleConstants.ASSET_ENTRY_CREATION_STATUSES); - - if (approvedArticlesCount > 0) { - addDraftAssetEntry = true; - } - } - - AssetEntry assetEntry = null; - - if (addDraftAssetEntry) { - assetEntry = assetEntryLocalService.updateEntry( - userId, article.getGroupId(), JournalArticle.class.getName(), - article.getPrimaryKey(), article.getUuid(), - getClassTypeId(article), assetCategoryIds, assetTagNames, false, - null, null, displayDate, expirationDate, ContentTypes.TEXT_HTML, - article.getTitle(), article.getDescription(), - article.getDescription(), null, article.getLayoutUuid(), 0, 0, - null, false); - } - else { - JournalArticleResource journalArticleResource = - journalArticleResourceLocalService.getArticleResource( - article.getResourcePrimKey()); - - assetEntry = assetEntryLocalService.updateEntry( - userId, article.getGroupId(), JournalArticle.class.getName(), - journalArticleResource.getResourcePrimKey(), - journalArticleResource.getUuid(), getClassTypeId(article), - assetCategoryIds, assetTagNames, visible, null, null, - displayDate, expirationDate, ContentTypes.TEXT_HTML, - article.getTitle(), article.getDescription(), - article.getDescription(), null, article.getLayoutUuid(), 0, 0, - null, false); - } - - assetLinkLocalService.updateLinks( - userId, assetEntry.getEntryId(), assetLinkEntryIds, - AssetLinkConstants.TYPE_RELATED); - } - - public JournalArticle updateContent( - long groupId, String articleId, double version, String content) - throws PortalException, SystemException { - - JournalArticle article = journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - - article.setContent(content); - - journalArticlePersistence.update(article, false); - - return article; - } - - public JournalArticle updateStatus( - long userId, JournalArticle article, int status, String articleURL, - ServiceContext serviceContext) - throws PortalException, SystemException { - - // Article - - User user = userPersistence.findByPrimaryKey(userId); - Date now = new Date(); - - int oldStatus = article.getStatus(); - - article.setModifiedDate(serviceContext.getModifiedDate(now)); - - boolean neverExpire = false; - - if (status == WorkflowConstants.STATUS_APPROVED) { - Date expirationDate = article.getExpirationDate(); - - if ((expirationDate != null) && expirationDate.before(now)) { - neverExpire = true; - - article.setExpirationDate(null); - } - } - - if (status == WorkflowConstants.STATUS_EXPIRED) { - article.setExpirationDate(now); - } - - article.setStatus(status); - article.setStatusByUserId(user.getUserId()); - article.setStatusByUserName(user.getFullName()); - article.setStatusDate(serviceContext.getModifiedDate(now)); - - journalArticlePersistence.update(article, false); - - if (isLatestVersion( - article.getGroupId(), article.getArticleId(), - article.getVersion())) { - - if (status == WorkflowConstants.STATUS_APPROVED) { - updateUrlTitles( - article.getGroupId(), article.getArticleId(), - article.getUrlTitle()); - - // Asset - - if ((oldStatus != WorkflowConstants.STATUS_APPROVED) && - (article.getVersion() != - JournalArticleConstants.VERSION_DEFAULT)) { - - AssetEntry draftAssetEntry = null; - - try { - draftAssetEntry = assetEntryLocalService.getEntry( - JournalArticle.class.getName(), - article.getPrimaryKey()); - - Date[] dateInterval = getDateInterval( - article.getGroupId(), article.getArticleId(), - article.getDisplayDate(), - article.getExpirationDate()); - - Date displayDate = dateInterval[0]; - Date expirationDate = dateInterval[1]; - - long[] assetCategoryIds = - draftAssetEntry.getCategoryIds(); - String[] assetTagNames = draftAssetEntry.getTagNames(); - - List assetLinks = - assetLinkLocalService.getDirectLinks( - draftAssetEntry.getEntryId(), - AssetLinkConstants.TYPE_RELATED); - - long[] assetLinkEntryIds = StringUtil.split( - ListUtil.toString( - assetLinks, AssetLink.ENTRY_ID2_ACCESSOR), 0L); - - boolean visible = true; - - if (article.getClassNameId() > 0) { - visible = false; - } - - AssetEntry assetEntry = - assetEntryLocalService.updateEntry( - userId, article.getGroupId(), - JournalArticle.class.getName(), - article.getResourcePrimKey(), article.getUuid(), - getClassTypeId(article), assetCategoryIds, - assetTagNames, visible, null, null, displayDate, - expirationDate, ContentTypes.TEXT_HTML, - article.getTitle(), article.getDescription(), - article.getDescription(), null, - article.getLayoutUuid(), 0, 0, null, false); - - assetLinkLocalService.updateLinks( - userId, assetEntry.getEntryId(), - assetLinkEntryIds, AssetLinkConstants.TYPE_RELATED); - - assetEntryLocalService.deleteEntry( - JournalArticle.class.getName(), - article.getPrimaryKey()); - } - catch (NoSuchEntryException nsee) { - } - } - - if (article.getClassNameId() == 0) { - AssetEntry assetEntry = - assetEntryLocalService.updateVisible( - JournalArticle.class.getName(), - article.getResourcePrimKey(), true); - - if (neverExpire) { - assetEntry.setExpirationDate(null); - - assetEntryLocalService.updateAssetEntry( - assetEntry, false); - } - } - - // Expando - - ExpandoBridge expandoBridge = article.getExpandoBridge(); - - expandoBridge.setAttributes(serviceContext); - - // Indexer - - Indexer indexer = IndexerRegistryUtil.getIndexer( - JournalArticle.class); - - indexer.reindex(article); - } - else if (oldStatus == WorkflowConstants.STATUS_APPROVED) { - updatePreviousApprovedArticle(article); - } - } - - if (article.getClassNameId() == 0) { - - // Email - - if ((oldStatus == WorkflowConstants.STATUS_PENDING) && - ((status == WorkflowConstants.STATUS_APPROVED) || - (status == WorkflowConstants.STATUS_DENIED))) { - - String msg = "granted"; - - if (status == WorkflowConstants.STATUS_DENIED) { - msg = "denied"; - } - - try { - PortletPreferences preferences = - ServiceContextUtil.getPortletPreferences( - serviceContext); - - sendEmail( - article, articleURL, preferences, msg, serviceContext); - } - catch (Exception e) { - _log.error( - "Unable to send email to notify the change of status " + - " to " + msg + " for article " + article.getId() + - ": " + e.getMessage()); - } - } - - // Subscriptions - - notifySubscribers(article, serviceContext); - } - - return article; - } - - public JournalArticle updateStatus( - long userId, long classPK, int status, - ServiceContext serviceContext) - throws PortalException, SystemException { - - JournalArticle article = getArticle(classPK); - - return updateStatus(userId, article, status, null, serviceContext); - } - - public JournalArticle updateStatus( - long userId, long groupId, String articleId, double version, - int status, String articleURL, ServiceContext serviceContext) - throws PortalException, SystemException { - - JournalArticle article = journalArticlePersistence.findByG_A_V( - groupId, articleId, version); - - return updateStatus( - userId, article, status, articleURL, serviceContext); - } - - public void updateTemplateId( - long groupId, long classNameId, String oldTemplateId, - String newTemplateId) - throws SystemException { - - List articles = journalArticlePersistence.findByG_C_T( - groupId, classNameId, oldTemplateId); - - for (JournalArticle article : articles) { - article.setTemplateId(newTemplateId); - - journalArticlePersistence.update(article, false); - } - } - - protected void checkStructure(Document contentDoc, Element root) - throws PortalException { - - for (Element el : root.elements()) { - checkStructureField(el, contentDoc); - - checkStructure(contentDoc, el); - } - } - - protected void checkStructure(JournalArticle article) - throws DocumentException, PortalException, SystemException { - - Group companyGroup = groupLocalService.getCompanyGroup( - article.getCompanyId()); - - JournalStructure structure = null; - - try { - structure = journalStructurePersistence.findByG_S( - article.getGroupId(), article.getStructureId()); - } - catch (NoSuchStructureException nsse) { - structure = journalStructurePersistence.findByG_S( - companyGroup.getGroupId(), article.getStructureId()); - } - - String content = GetterUtil.getString(article.getContent()); - - Document contentDoc = SAXReaderUtil.read(content); - Document xsdDoc = SAXReaderUtil.read(structure.getXsd()); - - try { - checkStructure(contentDoc, xsdDoc.getRootElement()); - } - catch (StructureXsdException sxsde) { - long groupId = article.getGroupId(); - String articleId = article.getArticleId(); - double version = article.getVersion(); - - if (_log.isWarnEnabled()) { - _log.warn( - "Article {groupId=" + groupId + ", articleId=" + - articleId + ", version=" + version + - "} has content that does not match its " + - "structure: " + sxsde.getMessage()); - } - } - } - - protected void checkStructureField(Element el, Document contentDoc) - throws PortalException { - - StringBuilder elPath = new StringBuilder(); - - elPath.append(el.attributeValue("name")); - - Element elParent = el.getParent(); - - for (;;) { - if ((elParent == null) || (elParent.getName().equals("root"))) { - break; - } - - elPath.insert( - 0, elParent.attributeValue("name") + StringPool.COMMA); - - elParent = elParent.getParent(); - } - - String[] elPathNames = StringUtil.split(elPath.toString()); - - Element contentEl = contentDoc.getRootElement(); - - for (String _elPathName : elPathNames) { - boolean foundEl = false; - - for (Element tempEl : contentEl.elements()) { - if (_elPathName.equals( - tempEl.attributeValue("name", StringPool.BLANK))) { - - contentEl = tempEl; - foundEl = true; - - break; - } - } - - if (!foundEl) { - String elType = contentEl.attributeValue( - "type", StringPool.BLANK); - - if (!elType.equals("list") && !elType.equals("multi-list")) { - throw new StructureXsdException(elPath.toString()); - } - - break; - } - } - } - - protected void copyArticleImages( - JournalArticle oldArticle, JournalArticle newArticle) - throws Exception { - - Document contentDoc = SAXReaderUtil.read(oldArticle.getContent()); - - XPath xPathSelector = SAXReaderUtil.createXPath( - "//dynamic-element[@type='image']"); - - List imageNodes = xPathSelector.selectNodes(contentDoc); - - for (Node imageNode : imageNodes) { - Element imageEl = (Element)imageNode; - - String instanceId = imageEl.attributeValue("instance-id"); - String name = imageEl.attributeValue("name"); - - List dynamicContentEls = imageEl.elements( - "dynamic-content"); - - for (Element dynamicContentEl : dynamicContentEls) { - long imageId = GetterUtil.getLong( - dynamicContentEl.attributeValue("id")); - String languageId = dynamicContentEl.attributeValue( - "language-id"); - - Image oldImage = null; - - try { - oldImage = imageLocalService.getImage(imageId); - } - catch (NoSuchImageException nsie) { - continue; - } - - imageId = journalArticleImageLocalService.getArticleImageId( - newArticle.getGroupId(), newArticle.getArticleId(), - newArticle.getVersion(), instanceId, name, languageId); - - imageLocalService.updateImage(imageId, oldImage.getTextObj()); - - String elContent = - "/image/journal/article?img_id=" + imageId + "&t=" + - WebServerServletTokenUtil.getToken(imageId); - - dynamicContentEl.setText(elContent); - dynamicContentEl.addAttribute("id", String.valueOf(imageId)); - } - } - - newArticle.setContent(contentDoc.formattedString()); - } - - protected void format( - User user, long groupId, String articleId, double version, - boolean incrementVersion, Element root, Map images) - throws PortalException, SystemException { - - for (Element element : root.elements()) { - String elInstanceId = element.attributeValue( - "instance-id", StringPool.BLANK); - String elName = element.attributeValue("name", StringPool.BLANK); - String elType = element.attributeValue("type", StringPool.BLANK); - - if (elType.equals("image")) { - formatImage( - groupId, articleId, version, incrementVersion, element, - elInstanceId, elName, images); - } - else if (elType.equals("text_area") || elType.equals("text") || - elType.equals("text_box")) { - - List dynamicContentElements = element.elements( - "dynamic-content"); - - for (Element dynamicContentElement : dynamicContentElements) { - String dynamicContent = dynamicContentElement.getText(); - - if (Validator.isNotNull(dynamicContent)) { - dynamicContent = SanitizerUtil.sanitize( - user.getCompanyId(), groupId, user.getUserId(), - JournalArticle.class.getName(), 0, - ContentTypes.TEXT_HTML, dynamicContent); - - dynamicContentElement.setText(dynamicContent); - } - } - } - - format( - user, groupId, articleId, version, incrementVersion, element, - images); - } - } - - protected String format( - User user, long groupId, String articleId, double version, - boolean incrementVersion, String content, String structureId, - Map images) - throws PortalException, SystemException { - - Document document = null; - - try { - document = SAXReaderUtil.read(content); - - Element rootElement = document.getRootElement(); - - if (Validator.isNotNull(structureId)) { - format( - user, groupId, articleId, version, incrementVersion, - rootElement, images); - } - else { - List staticContentElements = rootElement.elements( - "static-content"); - - for (Element staticContentElement : staticContentElements) { - String staticContent = staticContentElement.getText(); - - staticContent = SanitizerUtil.sanitize( - user.getCompanyId(), groupId, user.getUserId(), - JournalArticle.class.getName(), 0, - ContentTypes.TEXT_HTML, staticContent); - - staticContentElement.setText(staticContent); - } - } - - content = DDMXMLUtil.formatXML(document); - } - catch (DocumentException de) { - _log.error(de); - } - catch (IOException ioe) { - _log.error(ioe); - } - - content = HtmlUtil.replaceMsWordCharacters(content); - - return content; - } - - protected void formatImage( - long groupId, String articleId, double version, - boolean incrementVersion, Element el, String elInstanceId, - String elName, Map images) - throws PortalException, SystemException { - - List imageContents = el.elements("dynamic-content"); - - for (Element dynamicContent : imageContents) { - String elLanguage = dynamicContent.attributeValue( - "language-id", StringPool.BLANK); - - if (!elLanguage.equals(StringPool.BLANK)) { - elLanguage = "_" + elLanguage; - } - - long imageId = journalArticleImageLocalService.getArticleImageId( - groupId, articleId, version, elInstanceId, elName, elLanguage); - - double oldVersion = MathUtil.format(version - 0.1, 1, 1); - - long oldImageId = 0; - - if ((oldVersion >= 1) && incrementVersion) { - oldImageId = journalArticleImageLocalService.getArticleImageId( - groupId, articleId, oldVersion, elInstanceId, elName, - elLanguage); - } - - String elContent = - "/image/journal/article?img_id=" + imageId + "&t=" + - WebServerServletTokenUtil.getToken(imageId); - - if (dynamicContent.getText().equals("delete")) { - dynamicContent.setText(StringPool.BLANK); - - imageLocalService.deleteImage(imageId); - - String defaultElLanguage = ""; - - if (!Validator.isNotNull(elLanguage)) { - defaultElLanguage = - "_" + LocaleUtil.toLanguageId(LocaleUtil.getDefault()); - } - - long defaultImageId = - journalArticleImageLocalService.getArticleImageId( - groupId, articleId, version, elInstanceId, elName, - defaultElLanguage); - - imageLocalService.deleteImage(defaultImageId); - - continue; - } - - byte[] bytes = images.get(elInstanceId + "_" + elName + elLanguage); - - if ((bytes != null) && (bytes.length > 0)) { - dynamicContent.setText(elContent); - dynamicContent.addAttribute("id", String.valueOf(imageId)); - - imageLocalService.updateImage(imageId, bytes); - - continue; - } - - if ((version > JournalArticleConstants.VERSION_DEFAULT) && - (incrementVersion)) { - - Image oldImage = null; - - if (oldImageId > 0) { - oldImage = imageLocalService.getImage(oldImageId); - } - - if (oldImage != null) { - dynamicContent.setText(elContent); - dynamicContent.addAttribute("id", String.valueOf(imageId)); - - bytes = oldImage.getTextObj(); - - imageLocalService.updateImage(imageId, bytes); - } - - continue; - } - - Image image = imageLocalService.getImage(imageId); - - if (image != null) { - dynamicContent.setText(elContent); - dynamicContent.addAttribute("id", String.valueOf(imageId)); - - continue; - } - - long contentImageId = GetterUtil.getLong(HttpUtil.getParameter( - dynamicContent.getText(), "img_id")); - - if (contentImageId <= 0) { - contentImageId = GetterUtil.getLong(HttpUtil.getParameter( - dynamicContent.getText(), "img_id", false)); - } - - if (contentImageId > 0) { - image = imageLocalService.getImage(contentImageId); - - if (image != null) { - dynamicContent.addAttribute( - "id", String.valueOf(contentImageId)); - - continue; - } - } - - String defaultElLanguage = ""; - - if (!Validator.isNotNull(elLanguage)) { - defaultElLanguage = - "_" + LocaleUtil.toLanguageId(LocaleUtil.getDefault()); - } - - long defaultImageId = - journalArticleImageLocalService.getArticleImageId( - groupId, articleId, version, elInstanceId, elName, - defaultElLanguage); - - Image defaultImage = imageLocalService.getImage(defaultImageId); - - if (defaultImage != null) { - dynamicContent.setText(elContent); - dynamicContent.addAttribute( - "id", String.valueOf(defaultImageId)); - - bytes = defaultImage.getTextObj(); - - imageLocalService.updateImage(defaultImageId, bytes); - - continue; - } - - if (Validator.isNotNull(elLanguage)) { - dynamicContent.setText(StringPool.BLANK); - } - } - } - - protected long getClassTypeId(JournalArticle article) { - long classTypeId = 0; - - try { - JournalStructure structure = journalStructurePersistence.fetchByG_S( - article.getGroupId(), article.getStructureId()); - - if (structure == null) { - Group companyGroup = groupLocalService.getCompanyGroup( - article.getCompanyId()); - - structure = journalStructurePersistence.fetchByG_S( - companyGroup.getGroupId(), article.getStructureId()); - } - - if (structure != null) { - classTypeId = structure.getId(); - } - } - catch (Exception e) { - _log.error(e, e); - } - - return classTypeId; - } - - protected Date[] getDateInterval( - long groupId, String articleId, Date earliestDisplayDate, - Date latestExpirationDate) - throws SystemException { - - Date[] dateInterval = new Date[2]; - - List articles = journalArticlePersistence.findByG_A_ST( - groupId, articleId, WorkflowConstants.STATUS_APPROVED); - - boolean expiringArticle = true; - - if (latestExpirationDate == null) { - expiringArticle = false; - } - - for (JournalArticle article : articles) { - if ((earliestDisplayDate == null) || - ((article.getDisplayDate() != null) && - earliestDisplayDate.after(article.getDisplayDate()))) { - - earliestDisplayDate = article.getDisplayDate(); - } - - if (expiringArticle && - ((latestExpirationDate == null) || - ((article.getExpirationDate() != null) && - latestExpirationDate.before(article.getExpirationDate())))) { - - latestExpirationDate = article.getExpirationDate(); - } - - if (expiringArticle && (article.getExpirationDate() == null) && - (latestExpirationDate != null)) { - - expiringArticle = false; - } - } - - dateInterval[0] = earliestDisplayDate; - dateInterval[1] = latestExpirationDate; - - return dateInterval; - } - - protected String getUniqueUrlTitle( - long id, long groupId, String articleId, String title) - throws PortalException, SystemException { - - String urlTitle = JournalUtil.getUrlTitle(id, title); - - String newUrlTitle = ModelHintsUtil.trimString( - JournalArticle.class.getName(), "urlTitle", urlTitle); - - for (int i = 1;; i++) { - JournalArticle article = null; - - try { - article = getArticleByUrlTitle(groupId, newUrlTitle); - } - catch (NoSuchArticleException nsae) { - } - - if ((article == null) || article.getArticleId().equals(articleId)) { - break; - } - else { - String suffix = StringPool.DASH + i; - - String prefix = newUrlTitle; - - if (newUrlTitle.length() > suffix.length()) { - prefix = newUrlTitle.substring( - 0, newUrlTitle.length() - suffix.length()); - } - - newUrlTitle = prefix + suffix; - } - } - - return newUrlTitle; - } - - protected void notifySubscribers( - JournalArticle article, ServiceContext serviceContext) - throws PortalException, SystemException { - - if (!article.isApproved()) { - return; - } - - String articleURL = PortalUtil.getControlPanelFullURL( - serviceContext.getScopeGroupId(), PortletKeys.JOURNAL, null); - - if (Validator.isNull(articleURL)) { - return; - } - - PortletPreferences preferences = - ServiceContextUtil.getPortletPreferences(serviceContext); - - if (preferences == null) { - long ownerId = article.getGroupId(); - int ownerType = PortletKeys.PREFS_OWNER_TYPE_GROUP; - long plid = PortletKeys.PREFS_PLID_SHARED; - String portletId = PortletKeys.JOURNAL; - String defaultPreferences = null; - - preferences = portletPreferencesLocalService.getPreferences( - article.getCompanyId(), ownerId, ownerType, plid, portletId, - defaultPreferences); - } - - if ((article.getVersion() == 1.0) && - JournalUtil.getEmailArticleAddedEnabled(preferences)) { - } - else if ((article.getVersion() != 1.0) && - JournalUtil.getEmailArticleUpdatedEnabled(preferences)) { - } - else { - return; - } - - String fromName = JournalUtil.getEmailFromName( - preferences, article.getCompanyId()); - String fromAddress = JournalUtil.getEmailFromAddress( - preferences, article.getCompanyId()); - - String subject = null; - String body = null; - - if (article.getVersion() == 1.0) { - subject = JournalUtil.getEmailArticleAddedSubject(preferences); - body = JournalUtil.getEmailArticleAddedBody(preferences); - } - else { - subject = JournalUtil.getEmailArticleUpdatedSubject(preferences); - body = JournalUtil.getEmailArticleUpdatedBody(preferences); - } - - SubscriptionSender subscriptionSender = new SubscriptionSender(); - - subscriptionSender.setBody(body); - subscriptionSender.setCompanyId(article.getCompanyId()); - subscriptionSender.setContextAttributes( - "[$ARTICLE_ID$]", article.getArticleId(), "[$ARTICLE_TITLE$]", - article.getTitle(serviceContext.getLanguageId()), "[$ARTICLE_URL$]", - articleURL, "[$ARTICLE_VERSION$]", article.getVersion()); - subscriptionSender.setContextUserPrefix("ARTICLE"); - subscriptionSender.setFrom(fromAddress, fromName); - subscriptionSender.setHtmlFormat(true); - subscriptionSender.setMailId("journal_article", article.getId()); - subscriptionSender.setPortletId(PortletKeys.JOURNAL); - subscriptionSender.setReplyToAddress(fromAddress); - subscriptionSender.setScopeGroupId(article.getGroupId()); - subscriptionSender.setServiceContext(serviceContext); - subscriptionSender.setSubject(subject); - subscriptionSender.setUserId(article.getUserId()); - - subscriptionSender.addPersistedSubscribers( - JournalArticle.class.getName(), article.getGroupId()); - - subscriptionSender.flushNotificationsAsync(); - } - - protected void saveImages( - boolean smallImage, long smallImageId, File smallImageFile, - byte[] smallImageBytes) - throws PortalException, SystemException { - - if (smallImage) { - if ((smallImageFile != null) && (smallImageBytes != null)) { - imageLocalService.updateImage(smallImageId, smallImageBytes); - } - } - else { - imageLocalService.deleteImage(smallImageId); - } - } - - protected void sendEmail( - JournalArticle article, String articleURL, - PortletPreferences preferences, String emailType, - ServiceContext serviceContext) - throws PortalException, SystemException { - - if (preferences == null) { - return; - } - else if (emailType.equals("denied") && - JournalUtil.getEmailArticleApprovalDeniedEnabled( - preferences)) { - } - else if (emailType.equals("granted") && - JournalUtil.getEmailArticleApprovalGrantedEnabled( - preferences)) { - } - else if (emailType.equals("requested") && - JournalUtil.getEmailArticleApprovalRequestedEnabled( - preferences)) { - } - else if (emailType.equals("review") && - JournalUtil.getEmailArticleReviewEnabled(preferences)) { - } - else { - return; - } - - Company company = companyPersistence.findByPrimaryKey( - article.getCompanyId()); - - User user = userPersistence.findByPrimaryKey(article.getUserId()); - - articleURL += - "&groupId=" + article.getGroupId() + "&articleId=" + - article.getArticleId() + "&version=" + article.getVersion(); - - String fromName = JournalUtil.getEmailFromName( - preferences, article.getCompanyId()); - String fromAddress = JournalUtil.getEmailFromAddress( - preferences, article.getCompanyId()); - - String toName = user.getFullName(); - String toAddress = user.getEmailAddress(); - - if (emailType.equals("requested") || emailType.equals("review")) { - String tempToName = fromName; - String tempToAddress = fromAddress; - - fromName = toName; - fromAddress = toAddress; - - toName = tempToName; - toAddress = tempToAddress; - } - - String subject = null; - String body = null; - - if (emailType.equals("denied")) { - subject = JournalUtil.getEmailArticleApprovalDeniedSubject( - preferences); - body = JournalUtil.getEmailArticleApprovalDeniedBody(preferences); - } - else if (emailType.equals("granted")) { - subject = JournalUtil.getEmailArticleApprovalGrantedSubject( - preferences); - body = JournalUtil.getEmailArticleApprovalGrantedBody(preferences); - } - else if (emailType.equals("requested")) { - subject = JournalUtil.getEmailArticleApprovalRequestedSubject( - preferences); - body = JournalUtil.getEmailArticleApprovalRequestedBody( - preferences); - } - else if (emailType.equals("review")) { - subject = JournalUtil.getEmailArticleReviewSubject(preferences); - body = JournalUtil.getEmailArticleReviewBody(preferences); - } - - SubscriptionSender subscriptionSender = new SubscriptionSender(); - - subscriptionSender.setBody(body); - subscriptionSender.setCompanyId(company.getCompanyId()); - subscriptionSender.setContextAttributes( - "[$ARTICLE_ID$]", article.getArticleId(), "[$ARTICLE_TITLE$]", - article.getTitle(serviceContext.getLanguageId()), "[$ARTICLE_URL$]", - articleURL, "[$ARTICLE_USER_NAME$]", article.getUserName(), - "[$ARTICLE_VERSION$]", article.getVersion()); - subscriptionSender.setContextUserPrefix("ARTICLE"); - subscriptionSender.setFrom(fromAddress, fromName); - subscriptionSender.setHtmlFormat(true); - subscriptionSender.setMailId("journal_article", article.getId()); - subscriptionSender.setPortletId(PortletKeys.JOURNAL); - subscriptionSender.setScopeGroupId(article.getGroupId()); - subscriptionSender.setServiceContext(serviceContext); - subscriptionSender.setSubject(subject); - subscriptionSender.setUserId(article.getUserId()); - - subscriptionSender.addRuntimeSubscribers(toAddress, toName); - - subscriptionSender.flushNotificationsAsync(); - } - - protected void updatePreviousApprovedArticle(JournalArticle article) - throws PortalException, SystemException { - - List approvedArticles = - journalArticlePersistence.findByG_A_ST( - article.getGroupId(), article.getArticleId(), - WorkflowConstants.STATUS_APPROVED, 0, 2); - - if (approvedArticles.isEmpty() || - ((approvedArticles.size() == 1) && - (article.getStatus() == WorkflowConstants.STATUS_APPROVED))) { - - if (article.isIndexable()) { - Indexer indexer = IndexerRegistryUtil.getIndexer( - JournalArticle.class); - - indexer.delete(article); - } - - assetEntryLocalService.updateVisible( - JournalArticle.class.getName(), article.getResourcePrimKey(), - false); - } - else { - JournalArticle previousApprovedArticle = approvedArticles.get(0); - - if (article.getStatus() == WorkflowConstants.STATUS_APPROVED) { - previousApprovedArticle = approvedArticles.get(1); - } - - if (article.isIndexable()) { - Indexer indexer = IndexerRegistryUtil.getIndexer( - JournalArticle.class); - - indexer.reindex(previousApprovedArticle); - } - } - } - - protected void updateUrlTitles( - long groupId, String articleId, String urlTitle) - throws SystemException { - - List articles = journalArticlePersistence.findByG_A( - groupId, articleId); - - for (JournalArticle article : articles) { - if (!article.getUrlTitle().equals(urlTitle)) { - article.setUrlTitle(urlTitle); - - journalArticlePersistence.update(article, false); - } - } - } - - protected void validate( - long companyId, long groupId, long classNameId, - Map titleMap, String content, String type, - String structureId, String templateId, boolean smallImage, - String smallImageURL, File smallImageFile, byte[] smallImageBytes) - throws PortalException, SystemException { - - Locale defaultLocale = LocaleUtil.fromLanguageId( - LocalizationUtil.getDefaultLocale(content)); - - if ((classNameId == 0) && - (titleMap.isEmpty() || - Validator.isNull(titleMap.get(defaultLocale)))) { - - throw new ArticleTitleException(); - } - else if (Validator.isNull(type)) { - throw new ArticleTypeException(); - } - - validateContent(content); - - if (Validator.isNotNull(structureId)) { - Group companyGroup = groupLocalService.getCompanyGroup(companyId); - - try { - journalStructurePersistence.findByG_S(groupId, structureId); - } - catch (NoSuchStructureException nsse) { - journalStructurePersistence.findByG_S( - companyGroup.getGroupId(), structureId); - } - - JournalTemplate template = null; - - if (Validator.isNotNull(templateId)) { - try { - template = journalTemplatePersistence.findByG_T( - groupId, templateId); - } - catch (NoSuchTemplateException nste) { - template = journalTemplatePersistence.findByG_T( - companyGroup.getGroupId(), templateId); - } - - if (!template.getStructureId().equals(structureId)) { - throw new NoSuchTemplateException(); - } - } - else if (classNameId == 0) { - throw new NoSuchTemplateException(); - } - } - - String[] imageExtensions = PrefsPropsUtil.getStringArray( - PropsKeys.JOURNAL_IMAGE_EXTENSIONS, StringPool.COMMA); - - if (smallImage && Validator.isNull(smallImageURL) && - (smallImageFile != null) && (smallImageBytes != null)) { - - String smallImageName = smallImageFile.getName(); - - if (smallImageName != null) { - boolean validSmallImageExtension = false; - - for (String _imageExtension : imageExtensions) { - if (StringPool.STAR.equals(_imageExtension) || - StringUtil.endsWith(smallImageName, _imageExtension)) { - - validSmallImageExtension = true; - - break; - } - } - - if (!validSmallImageExtension) { - throw new ArticleSmallImageNameException(smallImageName); - } - } - - long smallImageMaxSize = PrefsPropsUtil.getLong( - PropsKeys.JOURNAL_IMAGE_SMALL_MAX_SIZE); - - if ((smallImageMaxSize > 0) && - ((smallImageBytes == null) || - (smallImageBytes.length > smallImageMaxSize))) { - - throw new ArticleSmallImageSizeException(); - } - } - } - - protected void validate( - long companyId, long groupId, long classNameId, String articleId, - boolean autoArticleId, double version, Map titleMap, - String content, String type, String structureId, String templateId, - boolean smallImage, String smallImageURL, File smallImageFile, - byte[] smallImageBytes) - throws PortalException, SystemException { - - if (!autoArticleId) { - validate(groupId, articleId); - } - - validate( - companyId, groupId, classNameId, titleMap, content, type, - structureId, templateId, smallImage, smallImageURL, smallImageFile, - smallImageBytes); - } - - protected void validate(long groupId, String articleId) - throws PortalException, SystemException { - - if ((Validator.isNull(articleId)) || - (articleId.indexOf(CharPool.SPACE) != -1)) { - - throw new ArticleIdException(); - } - - if (journalArticlePersistence.countByG_A(groupId, articleId) > 0) { - throw new DuplicateArticleIdException(); - } - } - - protected void validateContent(String content) throws PortalException { - if (Validator.isNull(content)) { - throw new ArticleContentException(); - } - - try { - SAXReaderUtil.read(content); - } - catch (DocumentException de) { - throw new ArticleContentException(); - } - } - - private static final long _JOURNAL_ARTICLE_CHECK_INTERVAL = - PropsValues.JOURNAL_ARTICLE_CHECK_INTERVAL * Time.MINUTE; - - private static Log _log = LogFactoryUtil.getLog( - JournalArticleLocalServiceImpl.class); - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portlet.journal.service.impl; + +import com.liferay.portal.NoSuchImageException; +import com.liferay.portal.kernel.dao.orm.QueryUtil; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.sanitizer.SanitizerUtil; +import com.liferay.portal.kernel.search.Field; +import com.liferay.portal.kernel.search.Hits; +import com.liferay.portal.kernel.search.Indexer; +import com.liferay.portal.kernel.search.IndexerRegistryUtil; +import com.liferay.portal.kernel.search.QueryConfig; +import com.liferay.portal.kernel.search.SearchContext; +import com.liferay.portal.kernel.search.Sort; +import com.liferay.portal.kernel.util.CalendarFactoryUtil; +import com.liferay.portal.kernel.util.CharPool; +import com.liferay.portal.kernel.util.ContentTypes; +import com.liferay.portal.kernel.util.DateUtil; +import com.liferay.portal.kernel.util.FileUtil; +import com.liferay.portal.kernel.util.GetterUtil; +import com.liferay.portal.kernel.util.HtmlUtil; +import com.liferay.portal.kernel.util.HttpUtil; +import com.liferay.portal.kernel.util.ListUtil; +import com.liferay.portal.kernel.util.LocaleUtil; +import com.liferay.portal.kernel.util.LocalizationUtil; +import com.liferay.portal.kernel.util.MathUtil; +import com.liferay.portal.kernel.util.OrderByComparator; +import com.liferay.portal.kernel.util.PropsKeys; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.Time; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.kernel.workflow.WorkflowConstants; +import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil; +import com.liferay.portal.kernel.xml.Document; +import com.liferay.portal.kernel.xml.DocumentException; +import com.liferay.portal.kernel.xml.Element; +import com.liferay.portal.kernel.xml.Node; +import com.liferay.portal.kernel.xml.SAXReaderUtil; +import com.liferay.portal.kernel.xml.XPath; +import com.liferay.portal.model.Company; +import com.liferay.portal.model.Group; +import com.liferay.portal.model.Image; +import com.liferay.portal.model.ModelHintsUtil; +import com.liferay.portal.model.ResourceConstants; +import com.liferay.portal.model.User; +import com.liferay.portal.service.ServiceContext; +import com.liferay.portal.service.ServiceContextUtil; +import com.liferay.portal.servlet.filters.cache.CacheUtil; +import com.liferay.portal.theme.ThemeDisplay; +import com.liferay.portal.util.PortalUtil; +import com.liferay.portal.util.PortletKeys; +import com.liferay.portal.util.PrefsPropsUtil; +import com.liferay.portal.util.PropsValues; +import com.liferay.portal.util.SubscriptionSender; +import com.liferay.portal.webserver.WebServerServletTokenUtil; +import com.liferay.portlet.asset.NoSuchEntryException; +import com.liferay.portlet.asset.model.AssetEntry; +import com.liferay.portlet.asset.model.AssetLink; +import com.liferay.portlet.asset.model.AssetLinkConstants; +import com.liferay.portlet.dynamicdatamapping.util.DDMXMLUtil; +import com.liferay.portlet.expando.model.ExpandoBridge; +import com.liferay.portlet.journal.ArticleContentException; +import com.liferay.portlet.journal.ArticleDisplayDateException; +import com.liferay.portlet.journal.ArticleExpirationDateException; +import com.liferay.portlet.journal.ArticleIdException; +import com.liferay.portlet.journal.ArticleReviewDateException; +import com.liferay.portlet.journal.ArticleSmallImageNameException; +import com.liferay.portlet.journal.ArticleSmallImageSizeException; +import com.liferay.portlet.journal.ArticleTitleException; +import com.liferay.portlet.journal.ArticleTypeException; +import com.liferay.portlet.journal.ArticleVersionException; +import com.liferay.portlet.journal.DuplicateArticleIdException; +import com.liferay.portlet.journal.NoSuchArticleException; +import com.liferay.portlet.journal.NoSuchArticleResourceException; +import com.liferay.portlet.journal.NoSuchStructureException; +import com.liferay.portlet.journal.NoSuchTemplateException; +import com.liferay.portlet.journal.StructureXsdException; +import com.liferay.portlet.journal.model.JournalArticle; +import com.liferay.portlet.journal.model.JournalArticleConstants; +import com.liferay.portlet.journal.model.JournalArticleDisplay; +import com.liferay.portlet.journal.model.JournalArticleResource; +import com.liferay.portlet.journal.model.JournalStructure; +import com.liferay.portlet.journal.model.JournalTemplate; +import com.liferay.portlet.journal.model.impl.JournalArticleDisplayImpl; +import com.liferay.portlet.journal.service.base.JournalArticleLocalServiceBaseImpl; +import com.liferay.portlet.journal.util.JournalUtil; +import com.liferay.portlet.journal.util.comparator.ArticleIDComparator; +import com.liferay.portlet.journal.util.comparator.ArticleVersionComparator; +import com.liferay.portlet.journalcontent.util.JournalContentUtil; + +import java.io.File; +import java.io.IOException; +import java.io.Serializable; + +import java.util.Calendar; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import javax.portlet.PortletPreferences; + +/** + * @author Brian Wing Shun Chan + * @author Raymond Augé + * @author Bruno Farache + * @author Juan Fernández + */ +public class JournalArticleLocalServiceImpl + extends JournalArticleLocalServiceBaseImpl { + + public JournalArticle addArticle( + long userId, long groupId, long classNameId, long classPK, + String articleId, boolean autoArticleId, double version, + Map titleMap, Map descriptionMap, + String content, String type, String structureId, String templateId, + String layoutUuid, int displayDateMonth, int displayDateDay, + int displayDateYear, int displayDateHour, int displayDateMinute, + int expirationDateMonth, int expirationDateDay, + int expirationDateYear, int expirationDateHour, + int expirationDateMinute, boolean neverExpire, int reviewDateMonth, + int reviewDateDay, int reviewDateYear, int reviewDateHour, + int reviewDateMinute, boolean neverReview, boolean indexable, + boolean smallImage, String smallImageURL, File smallImageFile, + Map images, String articleURL, + ServiceContext serviceContext) + throws PortalException, SystemException { + + // Article + + User user = userPersistence.findByPrimaryKey(userId); + articleId = articleId.trim().toUpperCase(); + + Date displayDate = PortalUtil.getDate( + displayDateMonth, displayDateDay, displayDateYear, displayDateHour, + displayDateMinute, user.getTimeZone(), + new ArticleDisplayDateException()); + + Date expirationDate = null; + + if (!neverExpire) { + expirationDate = PortalUtil.getDate( + expirationDateMonth, expirationDateDay, expirationDateYear, + expirationDateHour, expirationDateMinute, user.getTimeZone(), + new ArticleExpirationDateException()); + } + + Date reviewDate = null; + + if (!neverReview) { + reviewDate = PortalUtil.getDate( + reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour, + reviewDateMinute, user.getTimeZone(), + new ArticleReviewDateException()); + } + + byte[] smallImageBytes = null; + + try { + smallImageBytes = FileUtil.getBytes(smallImageFile); + } + catch (IOException ioe) { + } + + Date now = new Date(); + + validate( + user.getCompanyId(), groupId, classNameId, articleId, autoArticleId, + version, titleMap, content, type, structureId, templateId, + smallImage, smallImageURL, smallImageFile, smallImageBytes); + + if (autoArticleId) { + articleId = String.valueOf(counterLocalService.increment()); + } + + long id = counterLocalService.increment(); + + long resourcePrimKey = + journalArticleResourceLocalService.getArticleResourcePrimKey( + serviceContext.getUuid(), groupId, articleId); + + JournalArticle article = journalArticlePersistence.create(id); + + Locale locale = LocaleUtil.getDefault(); + + String defaultLanguageId = GetterUtil.getString( + serviceContext.getAttribute("defaultLanguageId")); + + if (Validator.isNotNull(defaultLanguageId)) { + locale = LocaleUtil.fromLanguageId(defaultLanguageId); + } + + String title = titleMap.get(locale); + + content = format( + user, groupId, articleId, version, false, content, structureId, + images); + + article.setResourcePrimKey(resourcePrimKey); + article.setGroupId(groupId); + article.setCompanyId(user.getCompanyId()); + article.setUserId(user.getUserId()); + article.setUserName(user.getFullName()); + article.setCreateDate(serviceContext.getCreateDate(now)); + article.setModifiedDate(serviceContext.getModifiedDate(now)); + article.setClassNameId(classNameId); + article.setClassPK(classPK); + article.setArticleId(articleId); + article.setVersion(version); + article.setTitleMap(titleMap, locale); + article.setUrlTitle(getUniqueUrlTitle(id, groupId, articleId, title)); + article.setDescriptionMap(descriptionMap, locale); + article.setContent(content); + article.setType(type); + article.setStructureId(structureId); + article.setTemplateId(templateId); + article.setLayoutUuid(layoutUuid); + article.setDisplayDate(displayDate); + article.setExpirationDate(expirationDate); + article.setReviewDate(reviewDate); + article.setIndexable(indexable); + article.setSmallImage(smallImage); + article.setSmallImageId(counterLocalService.increment()); + article.setSmallImageURL(smallImageURL); + + if ((expirationDate == null) || expirationDate.after(now)) { + article.setStatus(WorkflowConstants.STATUS_DRAFT); + } + else { + article.setStatus(WorkflowConstants.STATUS_EXPIRED); + } + + journalArticlePersistence.update(article, false); + + // Resources + + if (serviceContext.isAddGroupPermissions() || + serviceContext.isAddGuestPermissions()) { + + addArticleResources( + article, serviceContext.isAddGroupPermissions(), + serviceContext.isAddGuestPermissions()); + } + else { + addArticleResources( + article, serviceContext.getGroupPermissions(), + serviceContext.getGuestPermissions()); + } + + // Expando + + ExpandoBridge expandoBridge = article.getExpandoBridge(); + + expandoBridge.setAttributes(serviceContext); + + // Small image + + saveImages( + smallImage, article.getSmallImageId(), smallImageFile, + smallImageBytes); + + // Asset + + updateAsset( + userId, article, serviceContext.getAssetCategoryIds(), + serviceContext.getAssetTagNames(), + serviceContext.getAssetLinkEntryIds()); + + // Message boards + + if (PropsValues.JOURNAL_ARTICLE_COMMENTS_ENABLED) { + mbMessageLocalService.addDiscussionMessage( + userId, article.getUserName(), groupId, + JournalArticle.class.getName(), resourcePrimKey, + WorkflowConstants.ACTION_PUBLISH); + } + + // Email + + PortletPreferences preferences = + ServiceContextUtil.getPortletPreferences(serviceContext); + + sendEmail( + article, articleURL, preferences, "requested", serviceContext); + + // Workflow + + if (classNameId == 0) { + WorkflowHandlerRegistryUtil.startWorkflowInstance( + user.getCompanyId(), groupId, userId, + JournalArticle.class.getName(), article.getId(), article, + serviceContext); + + if (serviceContext.getWorkflowAction() != + WorkflowConstants.ACTION_PUBLISH) { + + // Indexer + + Indexer indexer = IndexerRegistryUtil.getIndexer( + JournalArticle.class); + + indexer.reindex(article); + } + } + else { + updateStatus( + userId, article, WorkflowConstants.STATUS_APPROVED, null, + serviceContext); + } + + return article; + } + + public void addArticleResources( + JournalArticle article, boolean addGroupPermissions, + boolean addGuestPermissions) + throws PortalException, SystemException { + + resourceLocalService.addResources( + article.getCompanyId(), article.getGroupId(), article.getUserId(), + JournalArticle.class.getName(), article.getResourcePrimKey(), false, + addGroupPermissions, addGuestPermissions); + } + + public void addArticleResources( + JournalArticle article, String[] groupPermissions, + String[] guestPermissions) + throws PortalException, SystemException { + + resourceLocalService.addModelResources( + article.getCompanyId(), article.getGroupId(), article.getUserId(), + JournalArticle.class.getName(), article.getResourcePrimKey(), + groupPermissions, guestPermissions); + } + + public void addArticleResources( + long groupId, String articleId, boolean addGroupPermissions, + boolean addGuestPermissions) + throws PortalException, SystemException { + + JournalArticle article = getLatestArticle(groupId, articleId); + + addArticleResources(article, addGroupPermissions, addGuestPermissions); + } + + public void addArticleResources( + long groupId, String articleId, String[] groupPermissions, + String[] guestPermissions) + throws PortalException, SystemException { + + JournalArticle article = getLatestArticle(groupId, articleId); + + addArticleResources(article, groupPermissions, guestPermissions); + } + + public JournalArticle checkArticleResourcePrimKey( + long groupId, String articleId, double version) + throws PortalException, SystemException { + + JournalArticle article = journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + + if (article.getResourcePrimKey() > 0) { + return article; + } + + long resourcePrimKey = + journalArticleResourceLocalService.getArticleResourcePrimKey( + groupId, articleId); + + article.setResourcePrimKey(resourcePrimKey); + + journalArticlePersistence.update(article, false); + + return article; + } + + public void checkArticles() throws PortalException, SystemException { + Date now = new Date(); + + List articles = + journalArticleFinder.findByExpirationDate( + 0, WorkflowConstants.STATUS_APPROVED, now); + + if (_log.isDebugEnabled()) { + _log.debug("Expiring " + articles.size() + " articles"); + } + + Set companyIds = new HashSet(); + + for (JournalArticle article : articles) { + article.setStatus(WorkflowConstants.STATUS_EXPIRED); + + journalArticlePersistence.update(article, false); + + if (article.isIndexable()) { + Indexer indexer = IndexerRegistryUtil.getIndexer( + JournalArticle.class); + + indexer.delete(article); + } + + updatePreviousApprovedArticle(article); + + JournalContentUtil.clearCache( + article.getGroupId(), article.getArticleId(), + article.getTemplateId()); + + companyIds.add(article.getCompanyId()); + } + + for (long companyId : companyIds) { + CacheUtil.clearCache(companyId); + } + + articles = journalArticleFinder.findByReviewDate( + 0, now, new Date(now.getTime() - _JOURNAL_ARTICLE_CHECK_INTERVAL)); + + if (_log.isDebugEnabled()) { + _log.debug( + "Sending review notifications for " + articles.size() + + " articles"); + } + + for (JournalArticle article : articles) { + String articleURL = StringPool.BLANK; + + long ownerId = article.getGroupId(); + int ownerType = PortletKeys.PREFS_OWNER_TYPE_GROUP; + long plid = PortletKeys.PREFS_PLID_SHARED; + String portletId = PortletKeys.JOURNAL; + + PortletPreferences preferences = + portletPreferencesLocalService.getPreferences( + article.getCompanyId(), ownerId, ownerType, plid, + portletId); + + sendEmail( + article, articleURL, preferences, "review", + new ServiceContext()); + } + } + + public void checkNewLine(long groupId, String articleId, double version) + throws PortalException, SystemException { + + JournalArticle article = journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + + String content = GetterUtil.getString(article.getContent()); + + if (content.indexOf("\\n") != -1) { + content = StringUtil.replace( + content, + new String[] {"\\n", "\\r"}, + new String[] {"\n", "\r"}); + + article.setContent(content); + + journalArticlePersistence.update(article, false); + } + } + + public void checkStructure(long groupId, String articleId, double version) + throws PortalException, SystemException { + + JournalArticle article = journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + + if (Validator.isNull(article.getStructureId())) { + return; + } + + try { + checkStructure(article); + } + catch (DocumentException de) { + _log.error(de, de); + } + } + + public JournalArticle copyArticle( + long userId, long groupId, String oldArticleId, String newArticleId, + boolean autoArticleId, double version) + throws PortalException, SystemException { + + // Article + + User user = userPersistence.findByPrimaryKey(userId); + oldArticleId = oldArticleId.trim().toUpperCase(); + newArticleId = newArticleId.trim().toUpperCase(); + Date now = new Date(); + + JournalArticle oldArticle = journalArticlePersistence.findByG_A_V( + groupId, oldArticleId, version); + + if (autoArticleId) { + newArticleId = String.valueOf(counterLocalService.increment()); + } + else { + validate(groupId, newArticleId); + } + + long id = counterLocalService.increment(); + + long resourcePrimKey = + journalArticleResourceLocalService.getArticleResourcePrimKey( + groupId, newArticleId); + + JournalArticle newArticle = journalArticlePersistence.create(id); + + newArticle.setResourcePrimKey(resourcePrimKey); + newArticle.setGroupId(groupId); + newArticle.setCompanyId(user.getCompanyId()); + newArticle.setUserId(user.getUserId()); + newArticle.setUserName(user.getFullName()); + newArticle.setCreateDate(now); + newArticle.setModifiedDate(now); + newArticle.setArticleId(newArticleId); + newArticle.setVersion(JournalArticleConstants.VERSION_DEFAULT); + newArticle.setTitle(oldArticle.getTitle()); + newArticle.setDescription(oldArticle.getDescription()); + + try { + copyArticleImages(oldArticle, newArticle); + } + catch (Exception e) { + newArticle.setContent(oldArticle.getContent()); + } + + newArticle.setType(oldArticle.getType()); + newArticle.setStructureId(oldArticle.getStructureId()); + newArticle.setTemplateId(oldArticle.getTemplateId()); + newArticle.setLayoutUuid(oldArticle.getLayoutUuid()); + newArticle.setDisplayDate(oldArticle.getDisplayDate()); + newArticle.setExpirationDate(oldArticle.getExpirationDate()); + newArticle.setReviewDate(oldArticle.getReviewDate()); + newArticle.setIndexable(oldArticle.isIndexable()); + newArticle.setSmallImage(oldArticle.isSmallImage()); + newArticle.setSmallImageId(counterLocalService.increment()); + newArticle.setSmallImageURL(oldArticle.getSmallImageURL()); + newArticle.setStatus(oldArticle.getStatus()); + + journalArticlePersistence.update(newArticle, false); + + // Resources + + addArticleResources(newArticle, true, true); + + // Small image + + if (oldArticle.getSmallImage()) { + Image image = imageLocalService.getImage( + oldArticle.getSmallImageId()); + + byte[] smallImageBytes = image.getTextObj(); + + imageLocalService.updateImage( + newArticle.getSmallImageId(), smallImageBytes); + } + + // Asset + + long[] assetCategoryIds = assetCategoryLocalService.getCategoryIds( + JournalArticle.class.getName(), oldArticle.getResourcePrimKey()); + String[] assetTagNames = assetTagLocalService.getTagNames( + JournalArticle.class.getName(), oldArticle.getResourcePrimKey()); + + updateAsset(userId, newArticle, assetCategoryIds, assetTagNames, null); + + return newArticle; + } + + public void deleteArticle( + JournalArticle article, String articleURL, + ServiceContext serviceContext) + throws PortalException, SystemException { + + if (article.isApproved() && + isLatestVersion( + article.getGroupId(), article.getArticleId(), + article.getVersion(), WorkflowConstants.STATUS_APPROVED)) { + + updatePreviousApprovedArticle(article); + } + + // Email + + PortletPreferences preferences = + ServiceContextUtil.getPortletPreferences(serviceContext); + + if ((preferences != null) && !article.isApproved() && + isLatestVersion( + article.getGroupId(), article.getArticleId(), + article.getVersion())) { + + sendEmail( + article, articleURL, preferences, "denied", serviceContext); + } + + // Images + + journalArticleImageLocalService.deleteImages( + article.getGroupId(), article.getArticleId(), article.getVersion()); + + // Workflow + + if (!article.isDraft()) { + workflowInstanceLinkLocalService.deleteWorkflowInstanceLink( + article.getCompanyId(), article.getGroupId(), + JournalArticle.class.getName(), article.getId()); + } + + int articlesCount = journalArticlePersistence.countByG_A( + article.getGroupId(), article.getArticleId()); + + if (articlesCount == 1) { + + // Ratings + + ratingsStatsLocalService.deleteStats( + JournalArticle.class.getName(), article.getResourcePrimKey()); + + // Message boards + + mbMessageLocalService.deleteDiscussionMessages( + JournalArticle.class.getName(), article.getResourcePrimKey()); + + // Asset + + assetEntryLocalService.deleteEntry( + JournalArticle.class.getName(), article.getResourcePrimKey()); + + // Content searches + + journalContentSearchLocalService.deleteArticleContentSearches( + article.getGroupId(), article.getArticleId()); + + // Small image + + imageLocalService.deleteImage(article.getSmallImageId()); + + // Expando + + expandoValueLocalService.deleteValues( + JournalArticle.class.getName(), article.getResourcePrimKey()); + + // Resources + + resourceLocalService.deleteResource( + article.getCompanyId(), JournalArticle.class.getName(), + ResourceConstants.SCOPE_INDIVIDUAL, + article.getResourcePrimKey()); + + // Resource + + try { + journalArticleResourceLocalService.deleteArticleResource( + article.getGroupId(), article.getArticleId()); + } + catch (NoSuchArticleResourceException nsare) { + } + } + + // Article + + journalArticlePersistence.remove(article); + } + + public void deleteArticle( + long groupId, String articleId, double version, String articleURL, + ServiceContext serviceContext) + throws PortalException, SystemException { + + JournalArticle article = journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + + deleteArticle(article, articleURL, serviceContext); + } + + public void deleteArticle( + long groupId, String articleId, ServiceContext serviceContext) + throws PortalException, SystemException { + + List articles = journalArticlePersistence.findByG_A( + groupId, articleId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, + new ArticleVersionComparator(true)); + + for (JournalArticle article : articles) { + deleteArticle(article, null, serviceContext); + } + } + + public void deleteArticles(long groupId) + throws PortalException, SystemException { + + for (JournalArticle article : + journalArticlePersistence.findByGroupId(groupId)) { + + deleteArticle(article, null, null); + } + } + + public void deleteLayoutArticleReferences(long groupId, String layoutUuid) + throws SystemException { + + List articles = journalArticlePersistence.findByG_L( + groupId, layoutUuid); + + for (JournalArticle article: articles) { + article.setLayoutUuid(StringPool.BLANK); + + journalArticlePersistence.update(article, false); + } + } + + public JournalArticle expireArticle( + long userId, long groupId, String articleId, double version, + String articleURL, ServiceContext serviceContext) + throws PortalException, SystemException { + + return updateStatus( + userId, groupId, articleId, version, + WorkflowConstants.STATUS_EXPIRED, articleURL, serviceContext); + } + + public void expireArticle( + long userId, long groupId, String articleId, String articleURL, + ServiceContext serviceContext) + throws PortalException, SystemException { + + List articles = journalArticlePersistence.findByG_A( + groupId, articleId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, + new ArticleVersionComparator(true)); + + for (JournalArticle article : articles) { + expireArticle( + userId, groupId, article.getArticleId(), article.getVersion(), + articleURL, serviceContext); + } + } + + public JournalArticle getArticle(long id) + throws PortalException, SystemException { + + return journalArticlePersistence.findByPrimaryKey(id); + } + + public JournalArticle getArticle(long groupId, String articleId) + throws PortalException, SystemException { + + // Get the latest article that is approved, if none are approved, get + // the latest unapproved article + + try { + return getLatestArticle( + groupId, articleId, WorkflowConstants.STATUS_APPROVED); + } + catch (NoSuchArticleException nsae) { + return getLatestArticle( + groupId, articleId, WorkflowConstants.STATUS_ANY); + } + } + + public JournalArticle getArticle( + long groupId, String articleId, double version) + throws PortalException, SystemException { + + return journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + } + + public JournalArticle getArticle( + long groupId, String className, long classPK) + throws PortalException, SystemException { + + long classNameId = PortalUtil.getClassNameId(className); + + List articles = journalArticlePersistence.findByG_C_C( + groupId, classNameId, classPK); + + if (articles.isEmpty()) { + throw new NoSuchArticleException( + "No approved JournalArticle exists with the key {groupId=" + + groupId + ", className=" + className + ", classPK=" + + classPK + "}"); + } + + return articles.get(0); + } + + public JournalArticle getArticleByUrlTitle(long groupId, String urlTitle) + throws PortalException, SystemException { + + // Get the latest article that is approved, if none are approved, get + // the latest unapproved article + + try { + return getLatestArticleByUrlTitle( + groupId, urlTitle, WorkflowConstants.STATUS_APPROVED); + } + catch (NoSuchArticleException nsae) { + return getLatestArticleByUrlTitle( + groupId, urlTitle, WorkflowConstants.STATUS_PENDING); + } + } + + public String getArticleContent( + JournalArticle article, String templateId, String viewMode, + String languageId, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + JournalArticleDisplay articleDisplay = getArticleDisplay( + article, templateId, viewMode, languageId, 1, null, themeDisplay); + + if (articleDisplay == null) { + return StringPool.BLANK; + } + else { + return articleDisplay.getContent(); + } + } + + public String getArticleContent( + long groupId, String articleId, double version, String viewMode, + String templateId, String languageId, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + JournalArticleDisplay articleDisplay = getArticleDisplay( + groupId, articleId, version, templateId, viewMode, languageId, + themeDisplay); + + if (articleDisplay == null) { + return StringPool.BLANK; + } + else { + return articleDisplay.getContent(); + } + } + + public String getArticleContent( + long groupId, String articleId, double version, String viewMode, + String languageId, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getArticleContent( + groupId, articleId, version, viewMode, null, languageId, + themeDisplay); + } + + public String getArticleContent( + long groupId, String articleId, String viewMode, String templateId, + String languageId, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + JournalArticleDisplay articleDisplay = getArticleDisplay( + groupId, articleId, templateId, viewMode, languageId, themeDisplay); + + return articleDisplay.getContent(); + } + + public String getArticleContent( + long groupId, String articleId, String viewMode, String languageId, + ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getArticleContent( + groupId, articleId, viewMode, null, languageId, themeDisplay); + } + + public JournalArticleDisplay getArticleDisplay( + JournalArticle article, String templateId, String viewMode, + String languageId, int page, String xmlRequest, + ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + String content = null; + + if (page < 1) { + page = 1; + } + + int numberOfPages = 1; + boolean paginate = false; + boolean pageFlow = false; + + boolean cacheable = true; + + if (Validator.isNull(xmlRequest)) { + xmlRequest = ""; + } + + Map tokens = JournalUtil.getTokens( + article.getGroupId(), themeDisplay, xmlRequest); + + tokens.put( + "article_resource_pk", + String.valueOf(article.getResourcePrimKey())); + + String defaultTemplateId = article.getTemplateId(); + + if (article.isTemplateDriven()) { + if (Validator.isNull(templateId)) { + templateId = defaultTemplateId; + } + + tokens.put("structure_id", article.getStructureId()); + tokens.put("template_id", templateId); + } + + String xml = article.getContent(); + + try { + Document document = null; + + Element rootElement = null; + + if (article.isTemplateDriven()) { + document = SAXReaderUtil.read(xml); + + rootElement = document.getRootElement(); + + Document requestDocument = SAXReaderUtil.read(xmlRequest); + + List pages = rootElement.elements("page"); + + if (!pages.isEmpty()) { + pageFlow = true; + + String targetPage = requestDocument.valueOf( + "/request/parameters/parameter[name='targetPage']/" + + "value"); + + Element pageElement = null; + + if (Validator.isNotNull(targetPage)) { + XPath xPathSelector = SAXReaderUtil.createXPath( + "/root/page[@id = '" + targetPage + "']"); + + pageElement = (Element)xPathSelector.selectSingleNode( + document); + } + + if (pageElement != null) { + document = SAXReaderUtil.createDocument(pageElement); + + rootElement = document.getRootElement(); + + numberOfPages = pages.size(); + } + else { + if (page > pages.size()) { + page = 1; + } + + pageElement = pages.get(page - 1); + + document = SAXReaderUtil.createDocument(pageElement); + + rootElement = document.getRootElement(); + + numberOfPages = pages.size(); + paginate = true; + } + } + + rootElement.add(requestDocument.getRootElement().createCopy()); + + JournalUtil.addAllReservedEls( + rootElement, tokens, article, languageId); + + xml = DDMXMLUtil.formatXML(document); + } + } + catch (DocumentException de) { + throw new SystemException(de); + } + catch (IOException ioe) { + throw new SystemException(ioe); + } + + try { + if (_log.isDebugEnabled()) { + _log.debug( + "Transforming " + article.getArticleId() + " " + + article.getVersion() + " " + languageId); + } + + String script = null; + String langType = null; + + if (article.isTemplateDriven()) { + + // Try with specified template first (in the current group and + // the global group). If a template is not specified, use the + // default one. If the specified template does not exit, use the + // default one. If the default one does not exist, throw an + // exception. + + JournalTemplate template = null; + + try { + template = journalTemplatePersistence.findByG_T( + article.getGroupId(), templateId); + } + catch (NoSuchTemplateException nste1) { + try { + Group companyGroup = groupLocalService.getCompanyGroup( + article.getCompanyId()); + + template = journalTemplatePersistence.findByG_T( + companyGroup.getGroupId(), templateId); + + tokens.put( + "company_group_id", + String.valueOf(companyGroup.getGroupId())); + } + catch (NoSuchTemplateException nste2) { + if (!defaultTemplateId.equals(templateId)) { + template = journalTemplatePersistence.findByG_T( + article.getGroupId(), defaultTemplateId); + } + else { + throw nste1; + } + } + } + + script = template.getXsl(); + langType = template.getLangType(); + cacheable = template.isCacheable(); + } + + content = JournalUtil.transform( + themeDisplay, tokens, viewMode, languageId, xml, script, + langType); + + if (!pageFlow) { + String[] pieces = StringUtil.split( + content, PropsValues.JOURNAL_ARTICLE_TOKEN_PAGE_BREAK); + + if (pieces.length > 1) { + if (page > pieces.length) { + page = 1; + } + + content = pieces[page - 1]; + numberOfPages = pieces.length; + paginate = true; + } + } + } + catch (Exception e) { + throw new SystemException(e); + } + + return new JournalArticleDisplayImpl( + article.getCompanyId(), article.getId(), + article.getResourcePrimKey(), article.getGroupId(), + article.getUserId(), article.getArticleId(), article.getVersion(), + article.getTitle(languageId), article.getUrlTitle(), + article.getDescription(languageId), article.getAvailableLocales(), + content, article.getType(), article.getStructureId(), templateId, + article.isSmallImage(), article.getSmallImageId(), + article.getSmallImageURL(), numberOfPages, page, paginate, + cacheable); + } + + public JournalArticleDisplay getArticleDisplay( + long groupId, String articleId, double version, String templateId, + String viewMode, String languageId, int page, String xmlRequest, + ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + Date now = new Date(); + + JournalArticle article = journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + + if (article.isExpired()) { + Date expirationDate = article.getExpirationDate(); + + if ((expirationDate != null) && expirationDate.before(now)) { + return null; + } + } + + if (article.getDisplayDate().after(now)) { + return null; + } + + return getArticleDisplay( + article, templateId, viewMode, languageId, page, xmlRequest, + themeDisplay); + } + + public JournalArticleDisplay getArticleDisplay( + long groupId, String articleId, double version, String templateId, + String viewMode, String languageId, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getArticleDisplay( + groupId, articleId, version, templateId, viewMode, languageId, 1, + null, themeDisplay); + } + + public JournalArticleDisplay getArticleDisplay( + long groupId, String articleId, String viewMode, String languageId, + int page, String xmlRequest, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getArticleDisplay( + groupId, articleId, null, viewMode, languageId, page, xmlRequest, + themeDisplay); + } + + public JournalArticleDisplay getArticleDisplay( + long groupId, String articleId, String templateId, String viewMode, + String languageId, int page, String xmlRequest, + ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + JournalArticle article = getDisplayArticle(groupId, articleId); + + return getArticleDisplay( + groupId, articleId, article.getVersion(), templateId, viewMode, + languageId, page, xmlRequest, themeDisplay); + } + + public JournalArticleDisplay getArticleDisplay( + long groupId, String articleId, String templateId, String viewMode, + String languageId, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + JournalArticle article = getDisplayArticle(groupId, articleId); + + return getArticleDisplay( + groupId, articleId, article.getVersion(), templateId, viewMode, + languageId, themeDisplay); + } + + public JournalArticleDisplay getArticleDisplay( + long groupId, String articleId, String viewMode, String languageId, + ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + return getArticleDisplay( + groupId, articleId, null, viewMode, languageId, themeDisplay); + } + + public List getArticles() throws SystemException { + return journalArticlePersistence.findAll(); + } + + public List getArticles(long groupId) + throws SystemException { + + return journalArticlePersistence.findByGroupId(groupId); + } + + public List getArticles(long groupId, int start, int end) + throws SystemException { + + return journalArticlePersistence.findByGroupId(groupId, start, end); + } + + public List getArticles( + long groupId, int start, int end, OrderByComparator obc) + throws SystemException { + + return journalArticlePersistence.findByGroupId( + groupId, start, end, obc); + } + + public List getArticles(long groupId, String articleId) + throws SystemException { + + return journalArticlePersistence.findByG_A(groupId, articleId); + } + + public List getArticlesBySmallImageId(long smallImageId) + throws SystemException { + + return journalArticlePersistence.findBySmallImageId(smallImageId); + } + + public int getArticlesCount(long groupId) throws SystemException { + return journalArticlePersistence.countByGroupId(groupId); + } + + public List getCompanyArticles( + long companyId, double version, int status, int start, int end) + throws SystemException { + + if (status == WorkflowConstants.STATUS_ANY) { + return journalArticlePersistence.findByC_V( + companyId, version, start, end, new ArticleIDComparator(true)); + } + else { + return journalArticlePersistence.findByC_V_ST( + companyId, version, status, start, end, + new ArticleIDComparator(true)); + } + } + + public List getCompanyArticles( + long companyId, int status, int start, int end) + throws SystemException { + + if (status == WorkflowConstants.STATUS_ANY) { + return journalArticlePersistence.findByCompanyId( + companyId, start, end, new ArticleIDComparator(true)); + } + else { + return journalArticlePersistence.findByC_ST( + companyId, status, start, end, new ArticleIDComparator(true)); + } + } + + public int getCompanyArticlesCount( + long companyId, double version, int status, int start, int end) + throws SystemException { + + if (status == WorkflowConstants.STATUS_ANY) { + return journalArticlePersistence.countByC_V(companyId, version); + } + else { + return journalArticlePersistence.countByC_V_ST( + companyId, version, status); + } + } + + public int getCompanyArticlesCount(long companyId, int status) + throws SystemException { + + if (status == WorkflowConstants.STATUS_ANY) { + return journalArticlePersistence.countByCompanyId(companyId); + } + else { + return journalArticlePersistence.countByC_ST(companyId, status); + } + } + + public JournalArticle getDisplayArticle(long groupId, String articleId) + throws PortalException, SystemException { + + List articles = journalArticlePersistence.findByG_A_ST( + groupId, articleId, WorkflowConstants.STATUS_APPROVED); + + if (articles.isEmpty()) { + throw new NoSuchArticleException( + "No approved JournalArticle exists with the key {groupId=" + + groupId + ", " + "articleId=" + articleId + "}"); + + } + + Date now = new Date(); + + for (int i = 0; i < articles.size(); i++) { + JournalArticle article = articles.get(i); + + Date expirationDate = article.getExpirationDate(); + + if (article.getDisplayDate().before(now) && + ((expirationDate == null) || expirationDate.after(now))) { + + return article; + } + } + + return articles.get(0); + } + + public JournalArticle getDisplayArticleByUrlTitle( + long groupId, String urlTitle) + throws PortalException, SystemException { + + List articles = null; + + OrderByComparator orderByComparator = new ArticleVersionComparator(); + + articles = journalArticlePersistence.findByG_UT_ST( + groupId, urlTitle, WorkflowConstants.STATUS_APPROVED, + QueryUtil.ALL_POS, QueryUtil.ALL_POS, orderByComparator); + + if (articles.isEmpty()) { + throw new NoSuchArticleException( + "No JournalArticle exists with the key {groupId=" + groupId + + ", urlTitle=" + urlTitle + "}"); + } + + Date now = new Date(); + + for (JournalArticle article : articles) { + Date expirationDate = article.getExpirationDate(); + + if (article.getDisplayDate().before(now) && + ((expirationDate == null) || expirationDate.after(now))) { + + return article; + } + } + + return articles.get(0); + } + + public JournalArticle getLatestArticle(long resourcePrimKey) + throws PortalException, SystemException { + + return getLatestArticle(resourcePrimKey, WorkflowConstants.STATUS_ANY); + } + + public JournalArticle getLatestArticle(long resourcePrimKey, int status) + throws PortalException, SystemException { + + return getLatestArticle(resourcePrimKey, status, true); + } + + public JournalArticle getLatestArticle( + long resourcePrimKey, int status, boolean preferApproved) + throws PortalException, SystemException { + + List articles = null; + + OrderByComparator orderByComparator = new ArticleVersionComparator(); + + if (status == WorkflowConstants.STATUS_ANY) { + if (preferApproved) { + articles = journalArticlePersistence.findByR_ST( + resourcePrimKey, WorkflowConstants.STATUS_APPROVED, 0, 1, + orderByComparator); + } + + if ((articles == null) || (articles.size() == 0)) { + articles = journalArticlePersistence.findByResourcePrimKey( + resourcePrimKey, 0, 1, orderByComparator); + } + } + else { + articles = journalArticlePersistence.findByR_ST( + resourcePrimKey, status, 0, 1, orderByComparator); + } + + if (articles.isEmpty()) { + throw new NoSuchArticleException( + "No JournalArticle exists with the key {resourcePrimKey=" + + resourcePrimKey + "}"); + } + + return articles.get(0); + } + + public JournalArticle getLatestArticle(long groupId, String articleId) + throws PortalException, SystemException { + + return getLatestArticle( + groupId, articleId, WorkflowConstants.STATUS_ANY); + } + + public JournalArticle getLatestArticle( + long groupId, String articleId, int status) + throws PortalException, SystemException { + + List articles = null; + + OrderByComparator orderByComparator = new ArticleVersionComparator(); + + if (status == WorkflowConstants.STATUS_ANY) { + articles = journalArticlePersistence.findByG_A( + groupId, articleId, 0, 1, orderByComparator); + } + else { + articles = journalArticlePersistence.findByG_A_ST( + groupId, articleId, status, 0, 1, orderByComparator); + } + + if (articles.isEmpty()) { + throw new NoSuchArticleException( + "No JournalArticle exists with the key {groupId=" + groupId + + ", articleId=" + articleId + ", status=" + status + "}"); + } + + return articles.get(0); + } + + public JournalArticle getLatestArticle( + long groupId, String className, long classPK) + throws PortalException, SystemException { + + long classNameId = PortalUtil.getClassNameId(className); + + List articles = journalArticlePersistence.findByG_C_C( + groupId, classNameId, classPK, 0, 1, + new ArticleVersionComparator()); + + if (articles.isEmpty()) { + throw new NoSuchArticleException( + "No JournalArticle exists with the key {groupId=" + groupId + + ", className=" + className + ", classPK =" + classPK + "}"); + } + + return articles.get(0); + } + + public JournalArticle getLatestArticleByUrlTitle( + long groupId, String urlTitle, int status) + throws PortalException, SystemException { + + List articles = null; + + OrderByComparator orderByComparator = new ArticleVersionComparator(); + + if (status == WorkflowConstants.STATUS_ANY) { + articles = journalArticlePersistence.findByG_UT( + groupId, urlTitle, 0, 1, orderByComparator); + } + else { + articles = journalArticlePersistence.findByG_UT_ST( + groupId, urlTitle, status, 0, 1, orderByComparator); + } + + if (articles.isEmpty()) { + throw new NoSuchArticleException( + "No JournalArticle exists with the key {groupId=" + groupId + + ", urlTitle=" + urlTitle + ", status=" + status + "}"); + } + + return articles.get(0); + } + + public double getLatestVersion(long groupId, String articleId) + throws PortalException, SystemException { + + JournalArticle article = getLatestArticle(groupId, articleId); + + return article.getVersion(); + } + + public double getLatestVersion(long groupId, String articleId, int status) + throws PortalException, SystemException { + + JournalArticle article = getLatestArticle(groupId, articleId, status); + + return article.getVersion(); + } + + public List getStructureArticles( + long groupId, String structureId) + throws SystemException { + + return journalArticlePersistence.findByG_S(groupId, structureId); + } + + public List getStructureArticles( + long groupId, String structureId, int start, int end, + OrderByComparator obc) + throws SystemException { + + return journalArticlePersistence.findByG_S( + groupId, structureId, start, end, obc); + } + + public int getStructureArticlesCount(long groupId, String structureId) + throws SystemException { + + return journalArticlePersistence.countByG_S(groupId, structureId); + } + + public List getTemplateArticles( + long groupId, String templateId) + throws SystemException { + + return journalArticlePersistence.findByG_T(groupId, templateId); + } + + public List getTemplateArticles( + long groupId, String templateId, int start, int end, + OrderByComparator obc) + throws SystemException { + + return journalArticlePersistence.findByG_T( + groupId, templateId, start, end, obc); + } + + public int getTemplateArticlesCount(long groupId, String templateId) + throws SystemException { + + return journalArticlePersistence.countByG_T(groupId, templateId); + } + + public boolean hasArticle(long groupId, String articleId) + throws SystemException { + + try { + getArticle(groupId, articleId); + + return true; + } + catch (PortalException pe) { + return false; + } + } + + public boolean isLatestVersion( + long groupId, String articleId, double version) + throws PortalException, SystemException { + + if (getLatestVersion(groupId, articleId) == version) { + return true; + } + else { + return false; + } + } + + public boolean isLatestVersion( + long groupId, String articleId, double version, int status) + throws PortalException, SystemException { + + if (getLatestVersion(groupId, articleId, status) == version) { + return true; + } + else { + return false; + } + } + + public JournalArticle removeArticleLocale( + long groupId, String articleId, double version, String languageId) + throws PortalException, SystemException { + + JournalArticle article = journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + + String title = article.getTitle(); + + title = LocalizationUtil.removeLocalization( + title, "static-content", languageId, true); + + article.setTitle(title); + + String description = article.getDescription(); + + description = LocalizationUtil.removeLocalization( + description, "static-content", languageId, true); + + article.setDescription(description); + + String content = article.getContent(); + + if (article.isTemplateDriven()) { + content = JournalUtil.removeArticleLocale(content, languageId); + } + else { + content = LocalizationUtil.removeLocalization( + content, "static-content", languageId, true); + } + + article.setContent(content); + + journalArticlePersistence.update(article, false); + + return article; + } + + public List search( + long companyId, long groupId, long classNameId, String keywords, + Double version, String type, String structureId, String templateId, + Date displayDateGT, Date displayDateLT, int status, Date reviewDate, + int start, int end, OrderByComparator obc) + throws SystemException { + + return journalArticleFinder.findByKeywords( + companyId, groupId, classNameId, keywords, version, type, + structureId, templateId, displayDateGT, displayDateLT, status, + reviewDate, start, end, obc); + } + + public List search( + long companyId, long groupId, long classNameId, String articleId, + Double version, String title, String description, String content, + String type, String structureId, String templateId, + Date displayDateGT, Date displayDateLT, int status, Date reviewDate, + boolean andOperator, int start, int end, OrderByComparator obc) + throws SystemException { + + return journalArticleFinder.findByC_G_C_A_V_T_D_C_T_S_T_D_S_R( + companyId, groupId, classNameId, articleId, version, title, + description, content, type, structureId, templateId, displayDateGT, + displayDateLT, status, reviewDate, andOperator, start, end, obc); + } + + public List search( + long companyId, long groupId, long classNameId, String articleId, + Double version, String title, String description, String content, + String type, String[] structureIds, String[] templateIds, + Date displayDateGT, Date displayDateLT, int status, Date reviewDate, + boolean andOperator, int start, int end, OrderByComparator obc) + throws SystemException { + + return journalArticleFinder.findByC_G_C_A_V_T_D_C_T_S_T_D_S_R( + companyId, groupId, classNameId, articleId, version, title, + description, content, type, structureIds, templateIds, + displayDateGT, displayDateLT, status, reviewDate, andOperator, + start, end, obc); + } + + public Hits search( + long companyId, long groupId, long classNameId, String structureId, + String templateId, String keywords, + LinkedHashMap params, int start, int end, Sort sort) + throws SystemException { + + String articleId = null; + String title = null; + String description = null; + String content = null; + boolean andOperator = false; + + if (Validator.isNotNull(keywords)) { + articleId = keywords; + title = keywords; + description = keywords; + content = keywords; + } + else { + andOperator = true; + } + + String status = String.valueOf(WorkflowConstants.STATUS_ANY); + + params.put("keywords", keywords); + + return search( + companyId, groupId, classNameId, articleId, title, description, + content, null, status, structureId, templateId, params, andOperator, + start, end, sort); + } + + public Hits search( + long companyId, long groupId, long classNameId, String articleId, + String title, String description, String content, String type, + String status, String structureId, String templateId, + LinkedHashMap params, boolean andSearch, int start, + int end, Sort sort) + throws SystemException { + + try { + SearchContext searchContext = new SearchContext(); + + searchContext.setAndSearch(andSearch); + + Map attributes = + new HashMap(); + + attributes.put(Field.CLASS_NAME_ID, classNameId); + attributes.put(Field.CONTENT, content); + attributes.put(Field.DESCRIPTION, description); + attributes.put(Field.STATUS, status); + attributes.put(Field.TITLE, title); + attributes.put(Field.TYPE, type); + attributes.put("articleId", articleId); + attributes.put("params", params); + attributes.put("structureId", structureId); + attributes.put("templateId", templateId); + + searchContext.setAttributes(attributes); + + searchContext.setCompanyId(companyId); + searchContext.setGroupIds(new long[] {groupId}); + searchContext.setEnd(end); + + String keywords = (String)params.remove("keywords"); + + if (Validator.isNotNull(keywords)) { + searchContext.setKeywords(keywords); + } + + QueryConfig queryConfig = new QueryConfig(); + + queryConfig.setHighlightEnabled(false); + queryConfig.setScoreEnabled(false); + + searchContext.setQueryConfig(queryConfig); + + searchContext.setSorts(new Sort[] {sort}); + searchContext.setStart(start); + + Indexer indexer = IndexerRegistryUtil.getIndexer( + JournalArticle.class); + + return indexer.search(searchContext); + } + catch (Exception e) { + throw new SystemException(e); + } + } + + public int searchCount( + long companyId, long groupId, long classNameId, String keywords, + Double version, String type, String structureId, String templateId, + Date displayDateGT, Date displayDateLT, int status, Date reviewDate) + throws SystemException { + + return journalArticleFinder.countByKeywords( + companyId, groupId, classNameId, keywords, version, type, + structureId, templateId, displayDateGT, displayDateLT, status, + reviewDate); + } + + public int searchCount( + long companyId, long groupId, long classNameId, String articleId, + Double version, String title, String description, String content, + String type, String structureId, String templateId, + Date displayDateGT, Date displayDateLT, int status, Date reviewDate, + boolean andOperator) + throws SystemException { + + return journalArticleFinder.countByC_G_C_A_V_T_D_C_T_S_T_D_S_R( + companyId, groupId, classNameId, articleId, version, title, + description, content, type, structureId, templateId, displayDateGT, + displayDateLT, status, reviewDate, andOperator); + } + + public int searchCount( + long companyId, long groupId, long classNameId, String articleId, + Double version, String title, String description, String content, + String type, String[] structureIds, String[] templateIds, + Date displayDateGT, Date displayDateLT, int status, Date reviewDate, + boolean andOperator) + throws SystemException { + + return journalArticleFinder.countByC_G_C_A_V_T_D_C_T_S_T_D_S_R( + companyId, groupId, classNameId, articleId, version, title, + description, content, type, structureIds, templateIds, + displayDateGT, displayDateLT, status, reviewDate, andOperator); + } + + public void subscribe(long userId, long groupId) + throws PortalException, SystemException { + + subscriptionLocalService.addSubscription( + userId, groupId, JournalArticle.class.getName(), groupId); + } + + public void unsubscribe(long userId, long groupId) + throws PortalException, SystemException { + + subscriptionLocalService.deleteSubscription( + userId, JournalArticle.class.getName(), groupId); + } + + public JournalArticle updateArticle( + long userId, long groupId, String articleId, double version, + Map titleMap, Map descriptionMap, + String content, String layoutUuid, ServiceContext serviceContext) + throws PortalException, SystemException { + + User user = userPersistence.findByPrimaryKey(userId); + + JournalArticle article = journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + + Date displayDate = article.getDisplayDate(); + + int displayDateMonth = 0; + int displayDateDay = 0; + int displayDateYear = 0; + int displayDateHour = 0; + int displayDateMinute = 0; + + if (displayDate != null) { + Calendar displayCal = CalendarFactoryUtil.getCalendar( + user.getTimeZone()); + + displayCal.setTime(displayDate); + + displayDateMonth = displayCal.get(Calendar.MONTH); + displayDateDay = displayCal.get(Calendar.DATE); + displayDateYear = displayCal.get(Calendar.YEAR); + displayDateHour = displayCal.get(Calendar.HOUR); + displayDateMinute = displayCal.get(Calendar.MINUTE); + + if (displayCal.get(Calendar.AM_PM) == Calendar.PM) { + displayDateHour += 12; + } + } + + Date expirationDate = article.getExpirationDate(); + + int expirationDateMonth = 0; + int expirationDateDay = 0; + int expirationDateYear = 0; + int expirationDateHour = 0; + int expirationDateMinute = 0; + boolean neverExpire = true; + + if (expirationDate != null) { + Calendar expirationCal = CalendarFactoryUtil.getCalendar( + user.getTimeZone()); + + expirationCal.setTime(expirationDate); + + expirationDateMonth = expirationCal.get(Calendar.MONTH); + expirationDateDay = expirationCal.get(Calendar.DATE); + expirationDateYear = expirationCal.get(Calendar.YEAR); + expirationDateHour = expirationCal.get(Calendar.HOUR); + expirationDateMinute = expirationCal.get(Calendar.MINUTE); + neverExpire = false; + + if (expirationCal.get(Calendar.AM_PM) == Calendar.PM) { + expirationDateHour += 12; + } + } + + Date reviewDate = article.getReviewDate(); + + int reviewDateMonth = 0; + int reviewDateDay = 0; + int reviewDateYear = 0; + int reviewDateHour = 0; + int reviewDateMinute = 0; + boolean neverReview = true; + + if (reviewDate != null) { + Calendar reviewCal = CalendarFactoryUtil.getCalendar( + user.getTimeZone()); + + reviewCal.setTime(reviewDate); + + reviewDateMonth = reviewCal.get(Calendar.MONTH); + reviewDateDay = reviewCal.get(Calendar.DATE); + reviewDateYear = reviewCal.get(Calendar.YEAR); + reviewDateHour = reviewCal.get(Calendar.HOUR); + reviewDateMinute = reviewCal.get(Calendar.MINUTE); + neverReview = false; + + if (reviewCal.get(Calendar.AM_PM) == Calendar.PM) { + reviewDateHour += 12; + } + } + + return updateArticle( + userId, groupId, articleId, version, titleMap, descriptionMap, + content, article.getType(), article.getStructureId(), + article.getTemplateId(), layoutUuid, displayDateMonth, + displayDateDay, displayDateYear, displayDateHour, displayDateMinute, + expirationDateMonth, expirationDateDay, expirationDateYear, + expirationDateHour, expirationDateMinute, neverExpire, + reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour, + reviewDateMinute, neverReview, article.getIndexable(), + article.isSmallImage(), article.getSmallImageURL(), null, null, + null, serviceContext); + } + + public JournalArticle updateArticle( + long userId, long groupId, String articleId, double version, + Map titleMap, Map descriptionMap, + String content, String type, String structureId, String templateId, + String layoutUuid, int displayDateMonth, int displayDateDay, + int displayDateYear, int displayDateHour, int displayDateMinute, + int expirationDateMonth, int expirationDateDay, + int expirationDateYear, int expirationDateHour, + int expirationDateMinute, boolean neverExpire, int reviewDateMonth, + int reviewDateDay, int reviewDateYear, int reviewDateHour, + int reviewDateMinute, boolean neverReview, boolean indexable, + boolean smallImage, String smallImageURL, File smallImageFile, + Map images, String articleURL, + ServiceContext serviceContext) + throws PortalException, SystemException { + + // Article + + User user = userPersistence.findByPrimaryKey(userId); + articleId = articleId.trim().toUpperCase(); + + Date displayDate = PortalUtil.getDate( + displayDateMonth, displayDateDay, displayDateYear, displayDateHour, + displayDateMinute, user.getTimeZone(), + new ArticleDisplayDateException()); + + Date expirationDate = null; + + if (!neverExpire) { + expirationDate = PortalUtil.getDate( + expirationDateMonth, expirationDateDay, expirationDateYear, + expirationDateHour, expirationDateMinute, user.getTimeZone(), + new ArticleExpirationDateException()); + } + + Date now = new Date(); + + boolean expired = false; + + if ((expirationDate != null) && expirationDate.before(now)) { + expired = true; + } + + Date reviewDate = null; + + if (!neverReview) { + reviewDate = PortalUtil.getDate( + reviewDateMonth, reviewDateDay, reviewDateYear, reviewDateHour, + reviewDateMinute, user.getTimeZone(), + new ArticleReviewDateException()); + } + + byte[] smallImageBytes = null; + + try { + smallImageBytes = FileUtil.getBytes(smallImageFile); + } + catch (IOException ioe) { + } + + JournalArticle oldArticle = null; + double oldVersion = 0; + + boolean incrementVersion = false; + + boolean imported = GetterUtil.getBoolean( + serviceContext.getAttribute("imported")); + + if (imported) { + oldArticle = getArticle(groupId, articleId, version); + oldVersion = version; + + if (expired) { + return expireArticle( + userId, groupId, articleId, version, articleURL, + serviceContext); + } + } + else { + oldArticle = getLatestArticle( + groupId, articleId, WorkflowConstants.STATUS_ANY); + + oldVersion = oldArticle.getVersion(); + + if ((version > 0) && (version != oldVersion)) { + throw new ArticleVersionException(); + } + + if (DateUtil.compareTo( + oldArticle.getModifiedDate(), serviceContext.getFormDate()) + > 0) { + + throw new ArticleVersionException(); + } + + if (oldArticle.isApproved() || oldArticle.isExpired()) { + incrementVersion = true; + } + } + + validate( + user.getCompanyId(), groupId, oldArticle.getClassNameId(), titleMap, + content, type, structureId, templateId, smallImage, smallImageURL, + smallImageFile, smallImageBytes); + + JournalArticle article = null; + + if (incrementVersion) { + double newVersion = MathUtil.format(oldVersion + 0.1, 1, 1); + + long id = counterLocalService.increment(); + + article = journalArticlePersistence.create(id); + + article.setResourcePrimKey(oldArticle.getResourcePrimKey()); + article.setGroupId(oldArticle.getGroupId()); + article.setCompanyId(oldArticle.getCompanyId()); + article.setUserId(user.getUserId()); + article.setUserName(user.getFullName()); + article.setCreateDate(serviceContext.getModifiedDate(now)); + article.setClassNameId(oldArticle.getClassNameId()); + article.setClassPK(oldArticle.getClassPK()); + article.setArticleId(articleId); + article.setVersion(newVersion); + article.setSmallImageId(oldArticle.getSmallImageId()); + } + else { + article = oldArticle; + } + + Locale locale = LocaleUtil.getDefault(); + + String defaultLanguageId = GetterUtil.getString( + serviceContext.getAttribute("defaultLanguageId")); + + if (Validator.isNotNull(defaultLanguageId)) { + locale = LocaleUtil.fromLanguageId(defaultLanguageId); + } + + String title = titleMap.get(locale); + + content = format( + user, groupId, articleId, article.getVersion(), incrementVersion, + content, structureId, images); + + article.setModifiedDate(serviceContext.getModifiedDate(now)); + article.setTitleMap(titleMap, locale); + article.setUrlTitle( + getUniqueUrlTitle(article.getId(), groupId, articleId, title)); + article.setDescriptionMap(descriptionMap, locale); + article.setContent(content); + article.setType(type); + article.setStructureId(structureId); + article.setTemplateId(templateId); + article.setLayoutUuid(layoutUuid); + article.setDisplayDate(displayDate); + article.setExpirationDate(expirationDate); + article.setReviewDate(reviewDate); + article.setIndexable(indexable); + article.setSmallImage(smallImage); + + if (article.getSmallImageId() == 0) { + article.setSmallImageId(counterLocalService.increment()); + } + + article.setSmallImageURL(smallImageURL); + + if (oldArticle.isPending()) { + article.setStatus(oldArticle.getStatus()); + } + else if (!expired) { + article.setStatus(WorkflowConstants.STATUS_DRAFT); + } + else { + article.setStatus(WorkflowConstants.STATUS_EXPIRED); + } + + journalArticlePersistence.update(article, false); + + // Asset + + updateAsset( + userId, article, serviceContext.getAssetCategoryIds(), + serviceContext.getAssetTagNames(), + serviceContext.getAssetLinkEntryIds()); + + // Expando + + ExpandoBridge expandoBridge = article.getExpandoBridge(); + + expandoBridge.setAttributes(serviceContext); + + // Small image + + saveImages( + smallImage, article.getSmallImageId(), smallImageFile, + smallImageBytes); + + // Email + + PortletPreferences preferences = + ServiceContextUtil.getPortletPreferences(serviceContext); + + // Workflow + + if (serviceContext.getWorkflowAction() == + WorkflowConstants.ACTION_PUBLISH) { + + sendEmail( + article, articleURL, preferences, "requested", serviceContext); + + WorkflowHandlerRegistryUtil.startWorkflowInstance( + user.getCompanyId(), groupId, userId, + JournalArticle.class.getName(), article.getId(), article, + serviceContext); + } + else if (article.getVersion() == + JournalArticleConstants.VERSION_DEFAULT) { + + // Indexer + + Indexer indexer = IndexerRegistryUtil.getIndexer( + JournalArticle.class); + + indexer.reindex(article); + } + + return article; + } + + public JournalArticle updateArticle( + long userId, long groupId, String articleId, double version, + String content, ServiceContext serviceContext) + throws PortalException, SystemException { + + JournalArticle article = journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + + return updateArticle( + userId, groupId, articleId, version, article.getTitleMap(), + article.getDescriptionMap(), content, article.getLayoutUuid(), + serviceContext); + } + + /** + * @deprecated {@link #updateArticleTranslation(long, String, double, + * Locale, String, String, String, Map, ServiceContext)} + */ + public JournalArticle updateArticleTranslation( + long groupId, String articleId, double version, Locale locale, + String title, String description, String content, + Map images) + throws PortalException, SystemException { + + return updateArticleTranslation( + groupId, articleId, version, locale, title, description, content, + images, null); + } + + public JournalArticle updateArticleTranslation( + long groupId, String articleId, double version, Locale locale, + String title, String description, String content, + Map images, ServiceContext serviceContext) + throws PortalException, SystemException { + + validateContent(content); + + JournalArticle oldArticle = getLatestArticle( + groupId, articleId, WorkflowConstants.STATUS_ANY); + + double oldVersion = oldArticle.getVersion(); + + if ((version > 0) && (version != oldVersion)) { + throw new ArticleVersionException(); + } + + if (serviceContext != null) { + if (DateUtil.compareTo( + oldArticle.getModifiedDate(), serviceContext.getFormDate()) + > 0) { + + throw new ArticleVersionException(); + } + } + + JournalArticle article = null; + + User user = userService.getUserById(oldArticle.getUserId()); + + if (!oldArticle.isDraft()) { + double newVersion = MathUtil.format(oldVersion + 0.1, 1, 1); + + long id = counterLocalService.increment(); + + article = journalArticlePersistence.create(id); + + article.setResourcePrimKey(oldArticle.getResourcePrimKey()); + article.setGroupId(oldArticle.getGroupId()); + article.setCompanyId(oldArticle.getCompanyId()); + article.setUserId(oldArticle.getUserId()); + article.setUserName(user.getFullName()); + article.setCreateDate(new Date()); + article.setModifiedDate(new Date()); + article.setClassNameId(oldArticle.getClassNameId()); + article.setClassPK(oldArticle.getClassPK()); + article.setArticleId(articleId); + article.setVersion(newVersion); + article.setTitleMap(oldArticle.getTitleMap()); + article.setUrlTitle( + getUniqueUrlTitle(article.getId(), groupId, articleId, title)); + article.setDescriptionMap(oldArticle.getDescriptionMap()); + article.setType(oldArticle.getType()); + article.setStructureId(oldArticle.getStructureId()); + article.setTemplateId(oldArticle.getTemplateId()); + article.setLayoutUuid(oldArticle.getLayoutUuid()); + article.setDisplayDate(oldArticle.getDisplayDate()); + article.setExpirationDate(oldArticle.getExpirationDate()); + article.setReviewDate(oldArticle.getReviewDate()); + article.setIndexable(oldArticle.getIndexable()); + article.setSmallImage(oldArticle.getSmallImage()); + article.setSmallImageId(oldArticle.getSmallImageId()); + + if (article.getSmallImageId() == 0) { + article.setSmallImageId(counterLocalService.increment()); + } + + article.setSmallImageURL(oldArticle.getSmallImageURL()); + + article.setStatus(WorkflowConstants.STATUS_DRAFT); + article.setStatusDate(new Date()); + } + else { + article = oldArticle; + } + + Map titleMap = article.getTitleMap(); + + titleMap.put(locale, title); + + article.setTitleMap(titleMap); + + Map descriptionMap = article.getDescriptionMap(); + + descriptionMap.put(locale, description); + + article.setDescriptionMap(descriptionMap); + + content = format( + user, groupId, articleId, version, !oldArticle.isDraft(), content, + oldArticle.getStructureId(), images); + + article.setContent(content); + + journalArticlePersistence.update(article, false); + + return article; + } + + public void updateAsset( + long userId, JournalArticle article, long[] assetCategoryIds, + String[] assetTagNames, long[] assetLinkEntryIds) + throws PortalException, SystemException { + + // Get the earliest display date and latest expiration date among + // all article versions + + Date[] dateInterval = getDateInterval( + article.getGroupId(), article.getArticleId(), + article.getDisplayDate(), article.getExpirationDate()); + + Date displayDate = dateInterval[0]; + Date expirationDate = dateInterval[1]; + + boolean visible = article.isApproved(); + + if (article.getClassNameId() > 0) { + visible = false; + } + + boolean addDraftAssetEntry = false; + + if (!article.isApproved() && + (article.getVersion() != JournalArticleConstants.VERSION_DEFAULT)) { + + int approvedArticlesCount = journalArticlePersistence.countByG_A_ST( + article.getGroupId(), article.getArticleId(), + JournalArticleConstants.ASSET_ENTRY_CREATION_STATUSES); + + if (approvedArticlesCount > 0) { + addDraftAssetEntry = true; + } + } + + AssetEntry assetEntry = null; + + if (addDraftAssetEntry) { + assetEntry = assetEntryLocalService.updateEntry( + userId, article.getGroupId(), JournalArticle.class.getName(), + article.getPrimaryKey(), article.getUuid(), + getClassTypeId(article), assetCategoryIds, assetTagNames, false, + null, null, displayDate, expirationDate, ContentTypes.TEXT_HTML, + article.getTitle(), article.getDescription(), + article.getDescription(), null, article.getLayoutUuid(), 0, 0, + null, false); + } + else { + JournalArticleResource journalArticleResource = + journalArticleResourceLocalService.getArticleResource( + article.getResourcePrimKey()); + + assetEntry = assetEntryLocalService.updateEntry( + userId, article.getGroupId(), JournalArticle.class.getName(), + journalArticleResource.getResourcePrimKey(), + journalArticleResource.getUuid(), getClassTypeId(article), + assetCategoryIds, assetTagNames, visible, null, null, + displayDate, expirationDate, ContentTypes.TEXT_HTML, + article.getTitle(), article.getDescription(), + article.getDescription(), null, article.getLayoutUuid(), 0, 0, + null, false); + } + + assetLinkLocalService.updateLinks( + userId, assetEntry.getEntryId(), assetLinkEntryIds, + AssetLinkConstants.TYPE_RELATED); + } + + public JournalArticle updateContent( + long groupId, String articleId, double version, String content) + throws PortalException, SystemException { + + JournalArticle article = journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + + article.setContent(content); + + journalArticlePersistence.update(article, false); + + return article; + } + + public JournalArticle updateStatus( + long userId, JournalArticle article, int status, String articleURL, + ServiceContext serviceContext) + throws PortalException, SystemException { + + // Article + + User user = userPersistence.findByPrimaryKey(userId); + Date now = new Date(); + + int oldStatus = article.getStatus(); + + article.setModifiedDate(serviceContext.getModifiedDate(now)); + + boolean neverExpire = false; + + if (status == WorkflowConstants.STATUS_APPROVED) { + Date expirationDate = article.getExpirationDate(); + + if ((expirationDate != null) && expirationDate.before(now)) { + neverExpire = true; + + article.setExpirationDate(null); + } + } + + if (status == WorkflowConstants.STATUS_EXPIRED) { + article.setExpirationDate(now); + } + + article.setStatus(status); + article.setStatusByUserId(user.getUserId()); + article.setStatusByUserName(user.getFullName()); + article.setStatusDate(serviceContext.getModifiedDate(now)); + + journalArticlePersistence.update(article, false); + + if (isLatestVersion( + article.getGroupId(), article.getArticleId(), + article.getVersion())) { + + if (status == WorkflowConstants.STATUS_APPROVED) { + updateUrlTitles( + article.getGroupId(), article.getArticleId(), + article.getUrlTitle()); + + // Asset + + if ((oldStatus != WorkflowConstants.STATUS_APPROVED) && + (article.getVersion() != + JournalArticleConstants.VERSION_DEFAULT)) { + + AssetEntry draftAssetEntry = null; + + try { + draftAssetEntry = assetEntryLocalService.getEntry( + JournalArticle.class.getName(), + article.getPrimaryKey()); + + Date[] dateInterval = getDateInterval( + article.getGroupId(), article.getArticleId(), + article.getDisplayDate(), + article.getExpirationDate()); + + Date displayDate = dateInterval[0]; + Date expirationDate = dateInterval[1]; + + long[] assetCategoryIds = + draftAssetEntry.getCategoryIds(); + String[] assetTagNames = draftAssetEntry.getTagNames(); + + List assetLinks = + assetLinkLocalService.getDirectLinks( + draftAssetEntry.getEntryId(), + AssetLinkConstants.TYPE_RELATED); + + long[] assetLinkEntryIds = StringUtil.split( + ListUtil.toString( + assetLinks, AssetLink.ENTRY_ID2_ACCESSOR), 0L); + + boolean visible = true; + + if (article.getClassNameId() > 0) { + visible = false; + } + + AssetEntry assetEntry = + assetEntryLocalService.updateEntry( + userId, article.getGroupId(), + JournalArticle.class.getName(), + article.getResourcePrimKey(), article.getUuid(), + getClassTypeId(article), assetCategoryIds, + assetTagNames, visible, null, null, displayDate, + expirationDate, ContentTypes.TEXT_HTML, + article.getTitle(), article.getDescription(), + article.getDescription(), null, + article.getLayoutUuid(), 0, 0, null, false); + + assetLinkLocalService.updateLinks( + userId, assetEntry.getEntryId(), assetLinkEntryIds, + AssetLinkConstants.TYPE_RELATED); + + assetEntryLocalService.deleteEntry( + JournalArticle.class.getName(), + article.getPrimaryKey()); + } + catch (NoSuchEntryException nsee) { + } + } + + if (article.getClassNameId() == 0) { + AssetEntry assetEntry = + assetEntryLocalService.updateVisible( + JournalArticle.class.getName(), + article.getResourcePrimKey(), true); + + if (neverExpire) { + assetEntry.setExpirationDate(null); + + assetEntryLocalService.updateAssetEntry( + assetEntry, false); + } + } + + // Expando + + ExpandoBridge expandoBridge = article.getExpandoBridge(); + + expandoBridge.setAttributes(serviceContext); + + // Indexer + + Indexer indexer = IndexerRegistryUtil.getIndexer( + JournalArticle.class); + + indexer.reindex(article); + } + else if (oldStatus == WorkflowConstants.STATUS_APPROVED) { + updatePreviousApprovedArticle(article); + } + } + + if (article.getClassNameId() == 0) { + + // Email + + if ((oldStatus == WorkflowConstants.STATUS_PENDING) && + ((status == WorkflowConstants.STATUS_APPROVED) || + (status == WorkflowConstants.STATUS_DENIED))) { + + String msg = "granted"; + + if (status == WorkflowConstants.STATUS_DENIED) { + msg = "denied"; + } + + try { + PortletPreferences preferences = + ServiceContextUtil.getPortletPreferences( + serviceContext); + + sendEmail( + article, articleURL, preferences, msg, serviceContext); + } + catch (Exception e) { + _log.error( + "Unable to send email to notify the change of status " + + " to " + msg + " for article " + article.getId() + + ": " + e.getMessage()); + } + } + + // Subscriptions + + notifySubscribers(article, serviceContext); + } + + return article; + } + + public JournalArticle updateStatus( + long userId, long classPK, int status, + ServiceContext serviceContext) + throws PortalException, SystemException { + + JournalArticle article = getArticle(classPK); + + return updateStatus(userId, article, status, null, serviceContext); + } + + public JournalArticle updateStatus( + long userId, long groupId, String articleId, double version, + int status, String articleURL, ServiceContext serviceContext) + throws PortalException, SystemException { + + JournalArticle article = journalArticlePersistence.findByG_A_V( + groupId, articleId, version); + + return updateStatus( + userId, article, status, articleURL, serviceContext); + } + + public void updateTemplateId( + long groupId, long classNameId, String oldTemplateId, + String newTemplateId) + throws SystemException { + + List articles = journalArticlePersistence.findByG_C_T( + groupId, classNameId, oldTemplateId); + + for (JournalArticle article : articles) { + article.setTemplateId(newTemplateId); + + journalArticlePersistence.update(article, false); + } + } + + protected void checkStructure(Document contentDoc, Element root) + throws PortalException { + + for (Element el : root.elements()) { + checkStructureField(el, contentDoc); + + checkStructure(contentDoc, el); + } + } + + protected void checkStructure(JournalArticle article) + throws DocumentException, PortalException, SystemException { + + Group companyGroup = groupLocalService.getCompanyGroup( + article.getCompanyId()); + + JournalStructure structure = null; + + try { + structure = journalStructurePersistence.findByG_S( + article.getGroupId(), article.getStructureId()); + } + catch (NoSuchStructureException nsse) { + structure = journalStructurePersistence.findByG_S( + companyGroup.getGroupId(), article.getStructureId()); + } + + String content = GetterUtil.getString(article.getContent()); + + Document contentDoc = SAXReaderUtil.read(content); + Document xsdDoc = SAXReaderUtil.read(structure.getXsd()); + + try { + checkStructure(contentDoc, xsdDoc.getRootElement()); + } + catch (StructureXsdException sxsde) { + long groupId = article.getGroupId(); + String articleId = article.getArticleId(); + double version = article.getVersion(); + + if (_log.isWarnEnabled()) { + _log.warn( + "Article {groupId=" + groupId + ", articleId=" + + articleId + ", version=" + version + + "} has content that does not match its " + + "structure: " + sxsde.getMessage()); + } + } + } + + protected void checkStructureField(Element el, Document contentDoc) + throws PortalException { + + StringBuilder elPath = new StringBuilder(); + + elPath.append(el.attributeValue("name")); + + Element elParent = el.getParent(); + + for (;;) { + if ((elParent == null) || (elParent.getName().equals("root"))) { + break; + } + + elPath.insert( + 0, elParent.attributeValue("name") + StringPool.COMMA); + + elParent = elParent.getParent(); + } + + String[] elPathNames = StringUtil.split(elPath.toString()); + + Element contentEl = contentDoc.getRootElement(); + + for (String _elPathName : elPathNames) { + boolean foundEl = false; + + for (Element tempEl : contentEl.elements()) { + if (_elPathName.equals( + tempEl.attributeValue("name", StringPool.BLANK))) { + + contentEl = tempEl; + foundEl = true; + + break; + } + } + + if (!foundEl) { + String elType = contentEl.attributeValue( + "type", StringPool.BLANK); + + if (!elType.equals("list") && !elType.equals("multi-list")) { + throw new StructureXsdException(elPath.toString()); + } + + break; + } + } + } + + protected void copyArticleImages( + JournalArticle oldArticle, JournalArticle newArticle) + throws Exception { + + Document contentDoc = SAXReaderUtil.read(oldArticle.getContent()); + + XPath xPathSelector = SAXReaderUtil.createXPath( + "//dynamic-element[@type='image']"); + + List imageNodes = xPathSelector.selectNodes(contentDoc); + + for (Node imageNode : imageNodes) { + Element imageEl = (Element)imageNode; + + String instanceId = imageEl.attributeValue("instance-id"); + String name = imageEl.attributeValue("name"); + + List dynamicContentEls = imageEl.elements( + "dynamic-content"); + + for (Element dynamicContentEl : dynamicContentEls) { + long imageId = GetterUtil.getLong( + dynamicContentEl.attributeValue("id")); + String languageId = dynamicContentEl.attributeValue( + "language-id"); + + Image oldImage = null; + + try { + oldImage = imageLocalService.getImage(imageId); + } + catch (NoSuchImageException nsie) { + continue; + } + + imageId = journalArticleImageLocalService.getArticleImageId( + newArticle.getGroupId(), newArticle.getArticleId(), + newArticle.getVersion(), instanceId, name, languageId); + + imageLocalService.updateImage(imageId, oldImage.getTextObj()); + + String elContent = + "/image/journal/article?img_id=" + imageId + "&t=" + + WebServerServletTokenUtil.getToken(imageId); + + dynamicContentEl.setText(elContent); + dynamicContentEl.addAttribute("id", String.valueOf(imageId)); + } + } + + newArticle.setContent(contentDoc.formattedString()); + } + + protected void format( + User user, long groupId, String articleId, double version, + boolean incrementVersion, Element root, Map images) + throws PortalException, SystemException { + + for (Element element : root.elements()) { + String elInstanceId = element.attributeValue( + "instance-id", StringPool.BLANK); + String elName = element.attributeValue("name", StringPool.BLANK); + String elType = element.attributeValue("type", StringPool.BLANK); + + if (elType.equals("image")) { + formatImage( + groupId, articleId, version, incrementVersion, element, + elInstanceId, elName, images); + } + else if (elType.equals("text_area") || elType.equals("text") || + elType.equals("text_box")) { + + List dynamicContentElements = element.elements( + "dynamic-content"); + + for (Element dynamicContentElement : dynamicContentElements) { + String dynamicContent = dynamicContentElement.getText(); + + if (Validator.isNotNull(dynamicContent)) { + dynamicContent = SanitizerUtil.sanitize( + user.getCompanyId(), groupId, user.getUserId(), + JournalArticle.class.getName(), 0, + ContentTypes.TEXT_HTML, dynamicContent); + + dynamicContentElement.setText(dynamicContent); + } + } + } + + format( + user, groupId, articleId, version, incrementVersion, element, + images); + } + } + + protected String format( + User user, long groupId, String articleId, double version, + boolean incrementVersion, String content, String structureId, + Map images) + throws PortalException, SystemException { + + Document document = null; + + try { + document = SAXReaderUtil.read(content); + + Element rootElement = document.getRootElement(); + + if (Validator.isNotNull(structureId)) { + format( + user, groupId, articleId, version, incrementVersion, + rootElement, images); + } + else { + List staticContentElements = rootElement.elements( + "static-content"); + + for (Element staticContentElement : staticContentElements) { + String staticContent = staticContentElement.getText(); + + staticContent = SanitizerUtil.sanitize( + user.getCompanyId(), groupId, user.getUserId(), + JournalArticle.class.getName(), 0, + ContentTypes.TEXT_HTML, staticContent); + + staticContentElement.setText(staticContent); + } + } + + content = DDMXMLUtil.formatXML(document); + } + catch (DocumentException de) { + _log.error(de); + } + catch (IOException ioe) { + _log.error(ioe); + } + + content = HtmlUtil.replaceMsWordCharacters(content); + + return content; + } + + protected void formatImage( + long groupId, String articleId, double version, + boolean incrementVersion, Element el, String elInstanceId, + String elName, Map images) + throws PortalException, SystemException { + + List imageContents = el.elements("dynamic-content"); + + for (Element dynamicContent : imageContents) { + String elLanguage = dynamicContent.attributeValue( + "language-id", StringPool.BLANK); + + if (!elLanguage.equals(StringPool.BLANK)) { + elLanguage = "_" + elLanguage; + } + + long imageId = journalArticleImageLocalService.getArticleImageId( + groupId, articleId, version, elInstanceId, elName, elLanguage); + + double oldVersion = MathUtil.format(version - 0.1, 1, 1); + + long oldImageId = 0; + + if ((oldVersion >= 1) && incrementVersion) { + oldImageId = journalArticleImageLocalService.getArticleImageId( + groupId, articleId, oldVersion, elInstanceId, elName, + elLanguage); + } + + String elContent = + "/image/journal/article?img_id=" + imageId + "&t=" + + WebServerServletTokenUtil.getToken(imageId); + + if (dynamicContent.getText().equals("delete")) { + dynamicContent.setText(StringPool.BLANK); + + imageLocalService.deleteImage(imageId); + + String defaultElLanguage = ""; + + if (!Validator.isNotNull(elLanguage)) { + defaultElLanguage = + "_" + LocaleUtil.toLanguageId(LocaleUtil.getDefault()); + } + + long defaultImageId = + journalArticleImageLocalService.getArticleImageId( + groupId, articleId, version, elInstanceId, elName, + defaultElLanguage); + + imageLocalService.deleteImage(defaultImageId); + + continue; + } + + byte[] bytes = images.get(elInstanceId + "_" + elName + elLanguage); + + if ((bytes != null) && (bytes.length > 0)) { + dynamicContent.setText(elContent); + dynamicContent.addAttribute("id", String.valueOf(imageId)); + + imageLocalService.updateImage(imageId, bytes); + + continue; + } + + if ((version > JournalArticleConstants.VERSION_DEFAULT) && + (incrementVersion)) { + + Image oldImage = null; + + if (oldImageId > 0) { + oldImage = imageLocalService.getImage(oldImageId); + } + + if (oldImage != null) { + dynamicContent.setText(elContent); + dynamicContent.addAttribute("id", String.valueOf(imageId)); + + bytes = oldImage.getTextObj(); + + imageLocalService.updateImage(imageId, bytes); + } + + continue; + } + + Image image = imageLocalService.getImage(imageId); + + if (image != null) { + dynamicContent.setText(elContent); + dynamicContent.addAttribute("id", String.valueOf(imageId)); + + continue; + } + + long contentImageId = GetterUtil.getLong(HttpUtil.getParameter( + dynamicContent.getText(), "img_id")); + + if (contentImageId <= 0) { + contentImageId = GetterUtil.getLong(HttpUtil.getParameter( + dynamicContent.getText(), "img_id", false)); + } + + if (contentImageId > 0) { + image = imageLocalService.getImage(contentImageId); + + if (image != null) { + dynamicContent.addAttribute( + "id", String.valueOf(contentImageId)); + + continue; + } + } + + String defaultElLanguage = ""; + + if (!Validator.isNotNull(elLanguage)) { + defaultElLanguage = + "_" + LocaleUtil.toLanguageId(LocaleUtil.getDefault()); + } + + long defaultImageId = + journalArticleImageLocalService.getArticleImageId( + groupId, articleId, version, elInstanceId, elName, + defaultElLanguage); + + Image defaultImage = imageLocalService.getImage(defaultImageId); + + if (defaultImage != null) { + dynamicContent.setText(elContent); + dynamicContent.addAttribute( + "id", String.valueOf(defaultImageId)); + + bytes = defaultImage.getTextObj(); + + imageLocalService.updateImage(defaultImageId, bytes); + + continue; + } + + if (Validator.isNotNull(elLanguage)) { + dynamicContent.setText(StringPool.BLANK); + } + } + } + + protected long getClassTypeId(JournalArticle article) { + long classTypeId = 0; + + try { + JournalStructure structure = journalStructurePersistence.fetchByG_S( + article.getGroupId(), article.getStructureId()); + + if (structure == null) { + Group companyGroup = groupLocalService.getCompanyGroup( + article.getCompanyId()); + + structure = journalStructurePersistence.fetchByG_S( + companyGroup.getGroupId(), article.getStructureId()); + } + + if (structure != null) { + classTypeId = structure.getId(); + } + } + catch (Exception e) { + _log.error(e, e); + } + + return classTypeId; + } + + protected Date[] getDateInterval( + long groupId, String articleId, Date earliestDisplayDate, + Date latestExpirationDate) + throws SystemException { + + Date[] dateInterval = new Date[2]; + + List articles = journalArticlePersistence.findByG_A_ST( + groupId, articleId, WorkflowConstants.STATUS_APPROVED); + + boolean expiringArticle = true; + + if (latestExpirationDate == null) { + expiringArticle = false; + } + + for (JournalArticle article : articles) { + if ((earliestDisplayDate == null) || + ((article.getDisplayDate() != null) && + earliestDisplayDate.after(article.getDisplayDate()))) { + + earliestDisplayDate = article.getDisplayDate(); + } + + if (expiringArticle && + ((latestExpirationDate == null) || + ((article.getExpirationDate() != null) && + latestExpirationDate.before(article.getExpirationDate())))) { + + latestExpirationDate = article.getExpirationDate(); + } + + if (expiringArticle && (article.getExpirationDate() == null) && + (latestExpirationDate != null)) { + + expiringArticle = false; + } + } + + dateInterval[0] = earliestDisplayDate; + dateInterval[1] = latestExpirationDate; + + return dateInterval; + } + + protected String getUniqueUrlTitle( + long id, long groupId, String articleId, String title) + throws PortalException, SystemException { + + String urlTitle = JournalUtil.getUrlTitle(id, title); + + String newUrlTitle = ModelHintsUtil.trimString( + JournalArticle.class.getName(), "urlTitle", urlTitle); + + for (int i = 1;; i++) { + JournalArticle article = null; + + try { + article = getArticleByUrlTitle(groupId, newUrlTitle); + } + catch (NoSuchArticleException nsae) { + } + + if ((article == null) || article.getArticleId().equals(articleId)) { + break; + } + else { + String suffix = StringPool.DASH + i; + + String prefix = newUrlTitle; + + if (newUrlTitle.length() > suffix.length()) { + prefix = newUrlTitle.substring( + 0, newUrlTitle.length() - suffix.length()); + } + + newUrlTitle = prefix + suffix; + } + } + + return newUrlTitle; + } + + protected void notifySubscribers( + JournalArticle article, ServiceContext serviceContext) + throws PortalException, SystemException { + + if (!article.isApproved()) { + return; + } + + String articleURL = PortalUtil.getControlPanelFullURL( + serviceContext.getScopeGroupId(), PortletKeys.JOURNAL, null); + + if (Validator.isNull(articleURL)) { + return; + } + + PortletPreferences preferences = + ServiceContextUtil.getPortletPreferences(serviceContext); + + if (preferences == null) { + long ownerId = article.getGroupId(); + int ownerType = PortletKeys.PREFS_OWNER_TYPE_GROUP; + long plid = PortletKeys.PREFS_PLID_SHARED; + String portletId = PortletKeys.JOURNAL; + String defaultPreferences = null; + + preferences = portletPreferencesLocalService.getPreferences( + article.getCompanyId(), ownerId, ownerType, plid, portletId, + defaultPreferences); + } + + if ((article.getVersion() == 1.0) && + JournalUtil.getEmailArticleAddedEnabled(preferences)) { + } + else if ((article.getVersion() != 1.0) && + JournalUtil.getEmailArticleUpdatedEnabled(preferences)) { + } + else { + return; + } + + String fromName = JournalUtil.getEmailFromName( + preferences, article.getCompanyId()); + String fromAddress = JournalUtil.getEmailFromAddress( + preferences, article.getCompanyId()); + + String subject = null; + String body = null; + + if (article.getVersion() == 1.0) { + subject = JournalUtil.getEmailArticleAddedSubject(preferences); + body = JournalUtil.getEmailArticleAddedBody(preferences); + } + else { + subject = JournalUtil.getEmailArticleUpdatedSubject(preferences); + body = JournalUtil.getEmailArticleUpdatedBody(preferences); + } + + SubscriptionSender subscriptionSender = new SubscriptionSender(); + + subscriptionSender.setBody(body); + subscriptionSender.setCompanyId(article.getCompanyId()); + subscriptionSender.setContextAttributes( + "[$ARTICLE_ID$]", article.getArticleId(), "[$ARTICLE_TITLE$]", + article.getTitle(serviceContext.getLanguageId()), "[$ARTICLE_URL$]", + articleURL, "[$ARTICLE_VERSION$]", article.getVersion()); + subscriptionSender.setContextUserPrefix("ARTICLE"); + subscriptionSender.setFrom(fromAddress, fromName); + subscriptionSender.setHtmlFormat(true); + subscriptionSender.setMailId("journal_article", article.getId()); + subscriptionSender.setPortletId(PortletKeys.JOURNAL); + subscriptionSender.setReplyToAddress(fromAddress); + subscriptionSender.setScopeGroupId(article.getGroupId()); + subscriptionSender.setServiceContext(serviceContext); + subscriptionSender.setSubject(subject); + subscriptionSender.setUserId(article.getUserId()); + + subscriptionSender.addPersistedSubscribers( + JournalArticle.class.getName(), article.getGroupId()); + + subscriptionSender.flushNotificationsAsync(); + } + + protected void saveImages( + boolean smallImage, long smallImageId, File smallImageFile, + byte[] smallImageBytes) + throws PortalException, SystemException { + + if (smallImage) { + if ((smallImageFile != null) && (smallImageBytes != null)) { + imageLocalService.updateImage(smallImageId, smallImageBytes); + } + } + else { + imageLocalService.deleteImage(smallImageId); + } + } + + protected void sendEmail( + JournalArticle article, String articleURL, + PortletPreferences preferences, String emailType, + ServiceContext serviceContext) + throws PortalException, SystemException { + + if (preferences == null) { + return; + } + else if (emailType.equals("denied") && + JournalUtil.getEmailArticleApprovalDeniedEnabled( + preferences)) { + } + else if (emailType.equals("granted") && + JournalUtil.getEmailArticleApprovalGrantedEnabled( + preferences)) { + } + else if (emailType.equals("requested") && + JournalUtil.getEmailArticleApprovalRequestedEnabled( + preferences)) { + } + else if (emailType.equals("review") && + JournalUtil.getEmailArticleReviewEnabled(preferences)) { + } + else { + return; + } + + Company company = companyPersistence.findByPrimaryKey( + article.getCompanyId()); + + User user = userPersistence.findByPrimaryKey(article.getUserId()); + + articleURL += + "&groupId=" + article.getGroupId() + "&articleId=" + + article.getArticleId() + "&version=" + article.getVersion(); + + String fromName = JournalUtil.getEmailFromName( + preferences, article.getCompanyId()); + String fromAddress = JournalUtil.getEmailFromAddress( + preferences, article.getCompanyId()); + + String toName = user.getFullName(); + String toAddress = user.getEmailAddress(); + + if (emailType.equals("requested") || emailType.equals("review")) { + String tempToName = fromName; + String tempToAddress = fromAddress; + + fromName = toName; + fromAddress = toAddress; + + toName = tempToName; + toAddress = tempToAddress; + } + + String subject = null; + String body = null; + + if (emailType.equals("denied")) { + subject = JournalUtil.getEmailArticleApprovalDeniedSubject( + preferences); + body = JournalUtil.getEmailArticleApprovalDeniedBody(preferences); + } + else if (emailType.equals("granted")) { + subject = JournalUtil.getEmailArticleApprovalGrantedSubject( + preferences); + body = JournalUtil.getEmailArticleApprovalGrantedBody(preferences); + } + else if (emailType.equals("requested")) { + subject = JournalUtil.getEmailArticleApprovalRequestedSubject( + preferences); + body = JournalUtil.getEmailArticleApprovalRequestedBody( + preferences); + } + else if (emailType.equals("review")) { + subject = JournalUtil.getEmailArticleReviewSubject(preferences); + body = JournalUtil.getEmailArticleReviewBody(preferences); + } + + SubscriptionSender subscriptionSender = new SubscriptionSender(); + + subscriptionSender.setBody(body); + subscriptionSender.setCompanyId(company.getCompanyId()); + subscriptionSender.setContextAttributes( + "[$ARTICLE_ID$]", article.getArticleId(), "[$ARTICLE_TITLE$]", + article.getTitle(serviceContext.getLanguageId()), "[$ARTICLE_URL$]", + articleURL, "[$ARTICLE_USER_NAME$]", article.getUserName(), + "[$ARTICLE_VERSION$]", article.getVersion()); + subscriptionSender.setContextUserPrefix("ARTICLE"); + subscriptionSender.setFrom(fromAddress, fromName); + subscriptionSender.setHtmlFormat(true); + subscriptionSender.setMailId("journal_article", article.getId()); + subscriptionSender.setPortletId(PortletKeys.JOURNAL); + subscriptionSender.setScopeGroupId(article.getGroupId()); + subscriptionSender.setServiceContext(serviceContext); + subscriptionSender.setSubject(subject); + subscriptionSender.setUserId(article.getUserId()); + + subscriptionSender.addRuntimeSubscribers(toAddress, toName); + + subscriptionSender.flushNotificationsAsync(); + } + + protected void updatePreviousApprovedArticle(JournalArticle article) + throws PortalException, SystemException { + + List approvedArticles = + journalArticlePersistence.findByG_A_ST( + article.getGroupId(), article.getArticleId(), + WorkflowConstants.STATUS_APPROVED, 0, 2); + + if (approvedArticles.isEmpty() || + ((approvedArticles.size() == 1) && + (article.getStatus() == WorkflowConstants.STATUS_APPROVED))) { + + if (article.isIndexable()) { + Indexer indexer = IndexerRegistryUtil.getIndexer( + JournalArticle.class); + + indexer.delete(article); + } + + assetEntryLocalService.updateVisible( + JournalArticle.class.getName(), article.getResourcePrimKey(), + false); + } + else { + JournalArticle previousApprovedArticle = approvedArticles.get(0); + + if (article.getStatus() == WorkflowConstants.STATUS_APPROVED) { + previousApprovedArticle = approvedArticles.get(1); + } + + if (article.isIndexable()) { + Indexer indexer = IndexerRegistryUtil.getIndexer( + JournalArticle.class); + + indexer.reindex(previousApprovedArticle); + } + } + } + + protected void updateUrlTitles( + long groupId, String articleId, String urlTitle) + throws SystemException { + + List articles = journalArticlePersistence.findByG_A( + groupId, articleId); + + for (JournalArticle article : articles) { + if (!article.getUrlTitle().equals(urlTitle)) { + article.setUrlTitle(urlTitle); + + journalArticlePersistence.update(article, false); + } + } + } + + protected void validate( + long companyId, long groupId, long classNameId, + Map titleMap, String content, String type, + String structureId, String templateId, boolean smallImage, + String smallImageURL, File smallImageFile, byte[] smallImageBytes) + throws PortalException, SystemException { + + Locale defaultLocale = LocaleUtil.fromLanguageId( + LocalizationUtil.getDefaultLocale(content)); + + if ((classNameId == 0) && + (titleMap.isEmpty() || + Validator.isNull(titleMap.get(defaultLocale)))) { + + throw new ArticleTitleException(); + } + else if (Validator.isNull(type)) { + throw new ArticleTypeException(); + } + + validateContent(content); + + if (Validator.isNotNull(structureId)) { + Group companyGroup = groupLocalService.getCompanyGroup(companyId); + + try { + journalStructurePersistence.findByG_S(groupId, structureId); + } + catch (NoSuchStructureException nsse) { + journalStructurePersistence.findByG_S( + companyGroup.getGroupId(), structureId); + } + + JournalTemplate template = null; + + if (Validator.isNotNull(templateId)) { + try { + template = journalTemplatePersistence.findByG_T( + groupId, templateId); + } + catch (NoSuchTemplateException nste) { + template = journalTemplatePersistence.findByG_T( + companyGroup.getGroupId(), templateId); + } + + if (!template.getStructureId().equals(structureId)) { + throw new NoSuchTemplateException(); + } + } + else if (classNameId == 0) { + throw new NoSuchTemplateException(); + } + } + + String[] imageExtensions = PrefsPropsUtil.getStringArray( + PropsKeys.JOURNAL_IMAGE_EXTENSIONS, StringPool.COMMA); + + if (smallImage && Validator.isNull(smallImageURL) && + (smallImageFile != null) && (smallImageBytes != null)) { + + String smallImageName = smallImageFile.getName(); + + if (smallImageName != null) { + boolean validSmallImageExtension = false; + + for (String _imageExtension : imageExtensions) { + if (StringPool.STAR.equals(_imageExtension) || + StringUtil.endsWith(smallImageName, _imageExtension)) { + + validSmallImageExtension = true; + + break; + } + } + + if (!validSmallImageExtension) { + throw new ArticleSmallImageNameException(smallImageName); + } + } + + long smallImageMaxSize = PrefsPropsUtil.getLong( + PropsKeys.JOURNAL_IMAGE_SMALL_MAX_SIZE); + + if ((smallImageMaxSize > 0) && + ((smallImageBytes == null) || + (smallImageBytes.length > smallImageMaxSize))) { + + throw new ArticleSmallImageSizeException(); + } + } + } + + protected void validate( + long companyId, long groupId, long classNameId, String articleId, + boolean autoArticleId, double version, Map titleMap, + String content, String type, String structureId, String templateId, + boolean smallImage, String smallImageURL, File smallImageFile, + byte[] smallImageBytes) + throws PortalException, SystemException { + + if (!autoArticleId) { + validate(groupId, articleId); + } + + validate( + companyId, groupId, classNameId, titleMap, content, type, + structureId, templateId, smallImage, smallImageURL, smallImageFile, + smallImageBytes); + } + + protected void validate(long groupId, String articleId) + throws PortalException, SystemException { + + if ((Validator.isNull(articleId)) || + (articleId.indexOf(CharPool.SPACE) != -1)) { + + throw new ArticleIdException(); + } + + if (journalArticlePersistence.countByG_A(groupId, articleId) > 0) { + throw new DuplicateArticleIdException(); + } + } + + protected void validateContent(String content) throws PortalException { + if (Validator.isNull(content)) { + throw new ArticleContentException(); + } + + try { + SAXReaderUtil.read(content); + } + catch (DocumentException de) { + throw new ArticleContentException(); + } + } + + private static final long _JOURNAL_ARTICLE_CHECK_INTERVAL = + PropsValues.JOURNAL_ARTICLE_CHECK_INTERVAL * Time.MINUTE; + + private static Log _log = LogFactoryUtil.getLog( + JournalArticleLocalServiceImpl.class); + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalStructureLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalStructureLocalServiceImpl.java index a49c180180c7fa..04cc67ddf3bc39 100644 --- a/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalStructureLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalStructureLocalServiceImpl.java @@ -144,8 +144,7 @@ public void addStructureResources( resourceLocalService.addResources( structure.getCompanyId(), structure.getGroupId(), structure.getUserId(), JournalStructure.class.getName(), - structure.getId(), false, addGroupPermissions, - addGuestPermissions); + structure.getId(), false, addGroupPermissions, addGuestPermissions); } public void addStructureResources( diff --git a/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalTemplateLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalTemplateLocalServiceImpl.java index f893784cd54794..8116ab906644ce 100644 --- a/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalTemplateLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalTemplateLocalServiceImpl.java @@ -172,8 +172,7 @@ public void addTemplateResources( resourceLocalService.addResources( template.getCompanyId(), template.getGroupId(), template.getUserId(), JournalTemplate.class.getName(), - template.getId(), false, addGroupPermissions, - addGuestPermissions); + template.getId(), false, addGroupPermissions, addGuestPermissions); } public void addTemplateResources( @@ -504,8 +503,7 @@ public int searchCount( public int searchCount( long companyId, long[] groupIds, String templateId, String structureId, String structureIdComparator, String name, - String description, - boolean andOperator) + String description, boolean andOperator) throws SystemException { return journalTemplateFinder.countByC_G_T_S_N_D( diff --git a/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalTemplateServiceImpl.java b/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalTemplateServiceImpl.java index 4e8931cf6ec3af..7ba74974845b88 100644 --- a/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalTemplateServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/journal/service/impl/JournalTemplateServiceImpl.java @@ -39,10 +39,9 @@ public class JournalTemplateServiceImpl extends JournalTemplateServiceBaseImpl { public JournalTemplate addTemplate( long groupId, String templateId, boolean autoTemplateId, String structureId, Map nameMap, - Map descriptionMap, String xsl, - boolean formatXsl, String langType, boolean cacheable, - boolean smallImage, String smallImageURL, File smallFile, - ServiceContext serviceContext) + Map descriptionMap, String xsl, boolean formatXsl, + String langType, boolean cacheable, boolean smallImage, + String smallImageURL, File smallFile, ServiceContext serviceContext) throws PortalException, SystemException { JournalPermission.check( @@ -57,9 +56,8 @@ public JournalTemplate addTemplate( public JournalTemplate addTemplate( long groupId, String templateId, boolean autoTemplateId, String structureId, Map nameMap, - Map descriptionMap, String xsl, - boolean formatXsl, String langType, boolean cacheable, - ServiceContext serviceContext) + Map descriptionMap, String xsl, boolean formatXsl, + String langType, boolean cacheable, ServiceContext serviceContext) throws PortalException, SystemException { JournalPermission.check( @@ -143,8 +141,7 @@ public int searchCount( public int searchCount( long companyId, long[] groupIds, String templateId, String structureId, String structureIdComparator, String name, - String description, - boolean andOperator) + String description, boolean andOperator) throws SystemException { return journalTemplateFinder.filterCountByC_G_T_S_N_D( diff --git a/portal-impl/src/com/liferay/portlet/journal/service/permission/JournalFeedPermission.java b/portal-impl/src/com/liferay/portlet/journal/service/permission/JournalFeedPermission.java index b50986103af4b3..9586c5df08c5fd 100644 --- a/portal-impl/src/com/liferay/portlet/journal/service/permission/JournalFeedPermission.java +++ b/portal-impl/src/com/liferay/portlet/journal/service/permission/JournalFeedPermission.java @@ -60,8 +60,8 @@ public static boolean contains( String actionId) { if (permissionChecker.hasOwnerPermission( - feed.getCompanyId(), JournalFeed.class.getName(), - feed.getId(), feed.getUserId(), actionId)) { + feed.getCompanyId(), JournalFeed.class.getName(), feed.getId(), + feed.getUserId(), actionId)) { return true; } diff --git a/portal-impl/src/com/liferay/portlet/journal/util/JournalOpenSearchImpl.java b/portal-impl/src/com/liferay/portlet/journal/util/JournalOpenSearchImpl.java index fe495e4e0915cf..e91fc0eeda387c 100644 --- a/portal-impl/src/com/liferay/portlet/journal/util/JournalOpenSearchImpl.java +++ b/portal-impl/src/com/liferay/portlet/journal/util/JournalOpenSearchImpl.java @@ -116,8 +116,8 @@ protected String getURL( if (Validator.isNotNull(article.getLayoutUuid())) { String groupFriendlyURL = PortalUtil.getGroupFriendlyURL( - GroupLocalServiceUtil.getGroup(article.getGroupId()), - false, themeDisplay); + GroupLocalServiceUtil.getGroup(article.getGroupId()), false, + themeDisplay); return groupFriendlyURL.concat( JournalArticleConstants.CANONICAL_URL_SEPARATOR).concat( diff --git a/portal-impl/src/com/liferay/portlet/journal/util/JournalUtil.java b/portal-impl/src/com/liferay/portlet/journal/util/JournalUtil.java index d64957d121ee65..593974a6797f87 100644 --- a/portal-impl/src/com/liferay/portlet/journal/util/JournalUtil.java +++ b/portal-impl/src/com/liferay/portlet/journal/util/JournalUtil.java @@ -99,8 +99,8 @@ public class JournalUtil { public static final int MAX_STACK_SIZE = 20; public static void addAllReservedEls( - Element rootElement, Map tokens, - JournalArticle article, String languageId) { + Element rootElement, Map tokens, JournalArticle article, + String languageId) { JournalUtil.addReservedEl( rootElement, tokens, JournalStructureConstants.RESERVED_ARTICLE_ID, @@ -289,8 +289,7 @@ public static void addReservedEl( // Tokens tokens.put( - StringUtil.replace(name, CharPool.DASH, CharPool.UNDERLINE), - value); + StringUtil.replace(name, CharPool.DASH, CharPool.UNDERLINE), value); } public static String formatVM(String vm) { diff --git a/portal-impl/src/com/liferay/portlet/journal/util/TokensTransformerListener.java b/portal-impl/src/com/liferay/portlet/journal/util/TokensTransformerListener.java index 34b83a1bd5f4ae..7bf721216a7936 100644 --- a/portal-impl/src/com/liferay/portlet/journal/util/TokensTransformerListener.java +++ b/portal-impl/src/com/liferay/portlet/journal/util/TokensTransformerListener.java @@ -114,13 +114,11 @@ protected String replace(String s) { } s = StringUtil.replace( - s, - escapedKeysList.toArray(new String[escapedKeysList.size()]), + s, escapedKeysList.toArray(new String[escapedKeysList.size()]), escapedValuesList.toArray(new String[escapedValuesList.size()])); s = StringUtil.replace( - s, - keysList.toArray(new String[keysList.size()]), + s, keysList.toArray(new String[keysList.size()]), valuesList.toArray(new String[valuesList.size()])); s = StringUtil.replace( diff --git a/portal-impl/src/com/liferay/portlet/layoutsadmin/action/EditLayoutSetAction.java b/portal-impl/src/com/liferay/portlet/layoutsadmin/action/EditLayoutSetAction.java index 4153292db18ee6..ed2087b6befd84 100644 --- a/portal-impl/src/com/liferay/portlet/layoutsadmin/action/EditLayoutSetAction.java +++ b/portal-impl/src/com/liferay/portlet/layoutsadmin/action/EditLayoutSetAction.java @@ -184,8 +184,8 @@ protected void updateLayoutSet( } protected void updateLogo( - ActionRequest actionRequest, long liveGroupId, - long stagingGroupId, boolean privateLayout, boolean hasLogo) + ActionRequest actionRequest, long liveGroupId, long stagingGroupId, + boolean privateLayout, boolean hasLogo) throws Exception { UploadPortletRequest uploadPortletRequest = diff --git a/portal-impl/src/com/liferay/portlet/layoutsadmin/action/EditLayoutsAction.java b/portal-impl/src/com/liferay/portlet/layoutsadmin/action/EditLayoutsAction.java index dd8064c90f92f2..b5e1521b3664cf 100644 --- a/portal-impl/src/com/liferay/portlet/layoutsadmin/action/EditLayoutsAction.java +++ b/portal-impl/src/com/liferay/portlet/layoutsadmin/action/EditLayoutsAction.java @@ -1,1088 +1,1086 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portlet.layoutsadmin.action; - -import com.liferay.portal.ImageTypeException; -import com.liferay.portal.LayoutFriendlyURLException; -import com.liferay.portal.LayoutHiddenException; -import com.liferay.portal.LayoutNameException; -import com.liferay.portal.LayoutParentLayoutIdException; -import com.liferay.portal.LayoutSetVirtualHostException; -import com.liferay.portal.LayoutTypeException; -import com.liferay.portal.NoSuchGroupException; -import com.liferay.portal.NoSuchLayoutException; -import com.liferay.portal.RemoteExportException; -import com.liferay.portal.RemoteOptionsException; -import com.liferay.portal.RequiredLayoutException; -import com.liferay.portal.events.EventsProcessorUtil; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.servlet.SessionErrors; -import com.liferay.portal.kernel.servlet.SessionMessages; -import com.liferay.portal.kernel.staging.StagingUtil; -import com.liferay.portal.kernel.upload.UploadException; -import com.liferay.portal.kernel.upload.UploadPortletRequest; -import com.liferay.portal.kernel.util.Constants; -import com.liferay.portal.kernel.util.FileUtil; -import com.liferay.portal.kernel.util.GetterUtil; -import com.liferay.portal.kernel.util.HttpUtil; -import com.liferay.portal.kernel.util.LocalizationUtil; -import com.liferay.portal.kernel.util.ParamUtil; -import com.liferay.portal.kernel.util.PropertiesParamUtil; -import com.liferay.portal.kernel.util.PropsKeys; -import com.liferay.portal.kernel.util.StringPool; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.kernel.util.UnicodeProperties; -import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.kernel.workflow.WorkflowConstants; -import com.liferay.portal.model.ColorScheme; -import com.liferay.portal.model.Group; -import com.liferay.portal.model.Layout; -import com.liferay.portal.model.LayoutConstants; -import com.liferay.portal.model.LayoutPrototype; -import com.liferay.portal.model.LayoutRevision; -import com.liferay.portal.model.LayoutSet; -import com.liferay.portal.model.LayoutSetBranch; -import com.liferay.portal.model.LayoutTypePortlet; -import com.liferay.portal.model.Theme; -import com.liferay.portal.model.ThemeSetting; -import com.liferay.portal.model.User; -import com.liferay.portal.model.impl.ThemeImpl; -import com.liferay.portal.model.impl.ThemeSettingImpl; -import com.liferay.portal.security.auth.PrincipalException; -import com.liferay.portal.security.permission.ActionKeys; -import com.liferay.portal.security.permission.PermissionChecker; -import com.liferay.portal.service.LayoutLocalServiceUtil; -import com.liferay.portal.service.LayoutPrototypeServiceUtil; -import com.liferay.portal.service.LayoutRevisionLocalServiceUtil; -import com.liferay.portal.service.LayoutServiceUtil; -import com.liferay.portal.service.LayoutSetBranchLocalServiceUtil; -import com.liferay.portal.service.LayoutSetLocalServiceUtil; -import com.liferay.portal.service.ServiceContext; -import com.liferay.portal.service.ServiceContextFactory; -import com.liferay.portal.service.ThemeLocalServiceUtil; -import com.liferay.portal.service.UserLocalServiceUtil; -import com.liferay.portal.service.permission.GroupPermissionUtil; -import com.liferay.portal.service.permission.LayoutPermissionUtil; -import com.liferay.portal.service.permission.LayoutPrototypePermissionUtil; -import com.liferay.portal.service.permission.LayoutSetPrototypePermissionUtil; -import com.liferay.portal.service.permission.OrganizationPermissionUtil; -import com.liferay.portal.service.permission.UserPermissionUtil; -import com.liferay.portal.struts.PortletAction; -import com.liferay.portal.theme.ThemeDisplay; -import com.liferay.portal.util.LayoutSettings; -import com.liferay.portal.util.PortalUtil; -import com.liferay.portal.util.PropsValues; -import com.liferay.portal.util.WebKeys; -import com.liferay.portlet.sites.action.ActionUtil; -import com.liferay.portlet.sites.util.SitesUtil; - -import java.io.IOException; -import java.io.InputStream; - -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import javax.portlet.ActionRequest; -import javax.portlet.ActionResponse; -import javax.portlet.PortletConfig; -import javax.portlet.PortletContext; -import javax.portlet.PortletRequest; -import javax.portlet.PortletRequestDispatcher; -import javax.portlet.RenderRequest; -import javax.portlet.RenderResponse; -import javax.portlet.ResourceRequest; -import javax.portlet.ResourceResponse; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.struts.action.ActionForm; -import org.apache.struts.action.ActionForward; -import org.apache.struts.action.ActionMapping; - -/** - * @author Brian Wing Shun Chan - * @author Julio Camarero - */ -public class EditLayoutsAction extends PortletAction { - - @Override - public void processAction( - ActionMapping mapping, ActionForm form, PortletConfig portletConfig, - ActionRequest actionRequest, ActionResponse actionResponse) - throws Exception { - - try { - checkPermissions(actionRequest); - } - catch (PrincipalException pe) { - return; - } - - ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute( - WebKeys.THEME_DISPLAY); - - String cmd = ParamUtil.getString(actionRequest, Constants.CMD); - - try { - String redirect = ParamUtil.getString(actionRequest, "redirect"); - String closeRedirect = ParamUtil.getString( - actionRequest, "closeRedirect"); - - Layout layout = null; - String oldFriendlyURL = StringPool.BLANK; - - if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) { - Object[] returnValue = updateLayout( - actionRequest, actionResponse); - - layout = (Layout)returnValue[0]; - oldFriendlyURL = (String)returnValue[1]; - - redirect = updateCloseRedirect( - redirect, null, layout, oldFriendlyURL); - closeRedirect = updateCloseRedirect( - closeRedirect, null, layout, oldFriendlyURL); - } - else if (cmd.equals(Constants.DELETE)) { - Object[] returnValue = SitesUtil.deleteLayout( - actionRequest, actionResponse); - - Group group = (Group)returnValue[0]; - oldFriendlyURL = (String)returnValue[1]; - long newRefererPlid = (Long)returnValue[2]; - - redirect = updateCloseRedirect( - redirect, group, null, oldFriendlyURL); - redirect = HttpUtil.setParameter( - redirect, "refererPlid", newRefererPlid); - - closeRedirect = updateCloseRedirect( - closeRedirect, group, null, oldFriendlyURL); - } - else if (cmd.equals("copy_from_live")) { - StagingUtil.copyFromLive(actionRequest); - } - else if (cmd.equals("display_order")) { - updateDisplayOrder(actionRequest); - } - else if (cmd.equals("delete_layout_revision")) { - deleteLayoutRevision(actionRequest); - } - else if (cmd.equals("enable")) { - enableLayout(actionRequest); - } - else if (cmd.equals("publish_to_live")) { - StagingUtil.publishToLive(actionRequest); - } - else if (cmd.equals("publish_to_remote")) { - StagingUtil.publishToRemote(actionRequest); - } - else if (cmd.equals("reset_customized_view")) { - LayoutTypePortlet layoutTypePortlet = - themeDisplay.getLayoutTypePortlet(); - - if ((layoutTypePortlet != null) && - layoutTypePortlet.isCustomizable() && - layoutTypePortlet.isCustomizedView()) { - - layoutTypePortlet.resetUserPreferences(); - } - } - else if (cmd.equals("reset_prototype")) { - SitesUtil.resetPrototype(themeDisplay.getLayout()); - } - else if (cmd.equals("schedule_copy_from_live")) { - StagingUtil.scheduleCopyFromLive(actionRequest); - } - else if (cmd.equals("schedule_publish_to_live")) { - StagingUtil.schedulePublishToLive(actionRequest); - } - else if (cmd.equals("schedule_publish_to_remote")) { - StagingUtil.schedulePublishToRemote(actionRequest); - } - else if (cmd.equals("select_layout_set_branch")) { - selectLayoutSetBranch(actionRequest); - } - else if (cmd.equals("select_layout_branch")) { - selectLayoutBranch(actionRequest); - } - else if (cmd.equals("unschedule_copy_from_live")) { - StagingUtil.unscheduleCopyFromLive(actionRequest); - } - else if (cmd.equals("unschedule_publish_to_live")) { - StagingUtil.unschedulePublishToLive(actionRequest); - } - else if (cmd.equals("unschedule_publish_to_remote")) { - StagingUtil.unschedulePublishToRemote(actionRequest); - } - else if (cmd.equals("update_layout_revision")) { - updateLayoutRevision(actionRequest, themeDisplay); - } - - if (Validator.isNotNull(closeRedirect)) { - SessionMessages.add( - actionRequest, - portletConfig.getPortletName() + - SessionMessages.KEY_SUFFIX_CLOSE_REDIRECT, - closeRedirect); - } - - sendRedirect(actionRequest, actionResponse, redirect); - } - catch (Exception e) { - if (e instanceof NoSuchLayoutException || - e instanceof PrincipalException) { - - SessionErrors.add(actionRequest, e.getClass().getName()); - - setForward(actionRequest, "portlet.layouts_admin.error"); - } - else if (e instanceof ImageTypeException || - e instanceof LayoutFriendlyURLException || - e instanceof LayoutHiddenException || - e instanceof LayoutNameException || - e instanceof LayoutParentLayoutIdException || - e instanceof LayoutSetVirtualHostException || - e instanceof LayoutTypeException || - e instanceof RequiredLayoutException || - e instanceof UploadException) { - - if (e instanceof LayoutFriendlyURLException) { - SessionErrors.add( - actionRequest, - LayoutFriendlyURLException.class.getName(), e); - } - else { - SessionErrors.add(actionRequest, e.getClass().getName(), e); - } - } - else if (e instanceof RemoteExportException || - e instanceof RemoteOptionsException || - e instanceof SystemException) { - - SessionErrors.add(actionRequest, e.getClass().getName(), e); - - String redirect = ParamUtil.getString( - actionRequest, "pagesRedirect"); - - sendRedirect(actionRequest, actionResponse, redirect); - } - else { - throw e; - } - } - } - - @Override - public ActionForward render( - ActionMapping mapping, ActionForm form, PortletConfig portletConfig, - RenderRequest renderRequest, RenderResponse renderResponse) - throws Exception { - - try { - checkPermissions(renderRequest); - } - catch (PrincipalException pe) { - SessionErrors.add( - renderRequest, PrincipalException.class.getName()); - - return mapping.findForward("portlet.layouts_admin.error"); - } - - try { - getGroup(renderRequest); - } - catch (Exception e) { - if (e instanceof NoSuchGroupException || - e instanceof PrincipalException) { - - SessionErrors.add(renderRequest, e.getClass().getName()); - - return mapping.findForward("portlet.layouts_admin.error"); - } - else { - throw e; - } - } - - return mapping.findForward( - getForward(renderRequest, "portlet.layouts_admin.edit_layouts")); - } - - @Override - public void serveResource( - ActionMapping mapping, ActionForm form, PortletConfig portletConfig, - ResourceRequest resourceRequest, ResourceResponse resourceResponse) - throws Exception { - - String cmd = ParamUtil.getString(resourceRequest, Constants.CMD); - - PortletContext portletContext = portletConfig.getPortletContext(); - - PortletRequestDispatcher portletRequestDispatcher = null; - - if (cmd.equals(ActionKeys.PUBLISH_STAGING)) { - portletRequestDispatcher = portletContext.getRequestDispatcher( - "/html/portlet/layouts_admin/scheduled_publishing_events.jsp"); - } - else if (cmd.equals(ActionKeys.VIEW_TREE)) { - getGroup(resourceRequest); - - portletRequestDispatcher = portletContext.getRequestDispatcher( - "/html/portlet/layouts_admin/tree_js.jsp"); - } - else { - getGroup(resourceRequest); - - portletRequestDispatcher = portletContext.getRequestDispatcher( - "/html/portlet/layouts_admin/view_resources.jsp"); - } - - portletRequestDispatcher.include(resourceRequest, resourceResponse); - } - - protected void checkPermissions(PortletRequest portletRequest) - throws Exception { - - // LEP-850 - - Group group = getGroup(portletRequest); - - if (group == null) { - throw new PrincipalException(); - } - - ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute( - WebKeys.THEME_DISPLAY); - - PermissionChecker permissionChecker = - themeDisplay.getPermissionChecker(); - - Layout layout = themeDisplay.getLayout(); - - String cmd = ParamUtil.getString(portletRequest, Constants.CMD); - - long selPlid = ParamUtil.getLong(portletRequest, "selPlid"); - - if (selPlid > 0) { - layout = LayoutLocalServiceUtil.getLayout(selPlid); - } - - if (cmd.equals(Constants.ADD)) { - long parentPlid = ParamUtil.getLong(portletRequest, "parentPlid"); - - if ((parentPlid == LayoutConstants.DEFAULT_PARENT_LAYOUT_ID)) { - if (!GroupPermissionUtil.contains( - permissionChecker, group.getGroupId(), - ActionKeys.ADD_LAYOUT)) { - - throw new PrincipalException(); - } - else { - return; - } - } - else { - layout = LayoutLocalServiceUtil.getLayout(parentPlid); - - if (!LayoutPermissionUtil.contains( - permissionChecker, layout, ActionKeys.ADD_LAYOUT)) { - - throw new PrincipalException(); - } - else { - return; - } - } - } - else if (cmd.equals(Constants.DELETE)) { - if (!LayoutPermissionUtil.contains( - permissionChecker, layout, ActionKeys.DELETE)) { - - throw new PrincipalException(); - } - else { - return; - } - } - else if (cmd.equals("reset_customized_view")) { - if (!LayoutPermissionUtil.contains( - permissionChecker, layout, ActionKeys.CUSTOMIZE)) { - - throw new PrincipalException(); - } - else { - return; - } - } - else if (cmd.equals("reset_prototype")) { - if (!LayoutPermissionUtil.contains( - permissionChecker, layout, ActionKeys.UPDATE) || - !GroupPermissionUtil.contains( - permissionChecker, layout.getGroupId(), - ActionKeys.UPDATE)) { - - throw new PrincipalException(); - } - else { - return; - } - } - - boolean hasUpdateLayoutPermission = false; - - if (layout != null) { - hasUpdateLayoutPermission = LayoutPermissionUtil.contains( - permissionChecker, layout, ActionKeys.UPDATE); - } - - boolean hasPermission = true; - - if (cmd.equals("publish_to_live")) { - if (group.isSite()) { - boolean publishToLive = GroupPermissionUtil.contains( - permissionChecker, group.getGroupId(), - ActionKeys.PUBLISH_STAGING); - - if (!hasUpdateLayoutPermission && !publishToLive) { - hasPermission = false; - } - } - else if (group.isOrganization()) { - boolean publishToLive = OrganizationPermissionUtil.contains( - permissionChecker, group.getOrganizationId(), - ActionKeys.PUBLISH_STAGING); - - if (!hasUpdateLayoutPermission && !publishToLive) { - hasPermission = false; - } - } - } - - if (group.isCompany()) { - if (!permissionChecker.isCompanyAdmin()) { - hasPermission = false; - } - } - else if (group.isLayoutPrototype()) { - LayoutPrototypePermissionUtil.check( - permissionChecker, group.getClassPK(), ActionKeys.UPDATE); - } - else if (group.isLayoutSetPrototype()) { - LayoutSetPrototypePermissionUtil.check( - permissionChecker, group.getClassPK(), ActionKeys.UPDATE); - } - else if (group.isUser()) { - long groupUserId = group.getClassPK(); - - User groupUser = UserLocalServiceUtil.getUserById(groupUserId); - - long[] organizationIds = groupUser.getOrganizationIds(); - - UserPermissionUtil.check( - permissionChecker, groupUserId, organizationIds, - ActionKeys.UPDATE); - } - - if (!hasPermission) { - throw new PrincipalException(); - } - } - - protected void deleteLayoutRevision(ActionRequest actionRequest) - throws Exception { - - HttpServletRequest request = PortalUtil.getHttpServletRequest( - actionRequest); - - long layoutRevisionId = ParamUtil.getLong( - actionRequest, "layoutRevisionId"); - - LayoutRevision layoutRevision = - LayoutRevisionLocalServiceUtil.getLayoutRevision(layoutRevisionId); - - LayoutRevisionLocalServiceUtil.deleteLayoutRevision(layoutRevision); - - boolean updateRecentLayoutRevisionId = ParamUtil.getBoolean( - actionRequest, "updateRecentLayoutRevisionId"); - - if (updateRecentLayoutRevisionId) { - StagingUtil.setRecentLayoutRevisionId( - request, layoutRevision.getLayoutSetBranchId(), - layoutRevision.getPlid(), - layoutRevision.getParentLayoutRevisionId()); - } - } - - protected void deleteThemeSettingsProperties( - UnicodeProperties typeSettingsProperties, String device) { - - String keyPrefix = ThemeSettingImpl.namespaceProperty(device); - - Set keys = typeSettingsProperties.keySet(); - - Iterator itr = keys.iterator(); - - while (itr.hasNext()) { - String key = itr.next(); - - if (key.startsWith(keyPrefix)) { - itr.remove(); - } - } - } - - protected void enableLayout(ActionRequest actionRequest) throws Exception { - long incompleteLayoutRevisionId = ParamUtil.getLong( - actionRequest, "incompleteLayoutRevisionId"); - - LayoutRevision incompleteLayoutRevision = - LayoutRevisionLocalServiceUtil.getLayoutRevision( - incompleteLayoutRevisionId); - - long layoutBranchId = ParamUtil.getLong( - actionRequest, "layoutBranchId", - incompleteLayoutRevision.getLayoutBranchId()); - - ServiceContext serviceContext = ServiceContextFactory.getInstance( - actionRequest); - - serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT); - - LayoutRevisionLocalServiceUtil.updateLayoutRevision( - serviceContext.getUserId(), - incompleteLayoutRevision.getLayoutRevisionId(), layoutBranchId, - incompleteLayoutRevision.getName(), - incompleteLayoutRevision.getTitle(), - incompleteLayoutRevision.getDescription(), - incompleteLayoutRevision.getKeywords(), - incompleteLayoutRevision.getRobots(), - incompleteLayoutRevision.getTypeSettings(), - incompleteLayoutRevision.getIconImage(), - incompleteLayoutRevision.getIconImageId(), - incompleteLayoutRevision.getThemeId(), - incompleteLayoutRevision.getColorSchemeId(), - incompleteLayoutRevision.getWapThemeId(), - incompleteLayoutRevision.getWapColorSchemeId(), - incompleteLayoutRevision.getCss(), serviceContext); - } - - protected String getColorSchemeId( - long companyId, String themeId, String colorSchemeId, - boolean wapTheme) - throws Exception { - - Theme theme = ThemeLocalServiceUtil.getTheme( - companyId, themeId, wapTheme); - - if (!theme.hasColorSchemes()) { - colorSchemeId = StringPool.BLANK; - } - - if (Validator.isNull(colorSchemeId)) { - ColorScheme colorScheme = ThemeLocalServiceUtil.getColorScheme( - companyId, themeId, colorSchemeId, wapTheme); - - colorSchemeId = colorScheme.getColorSchemeId(); - } - - return colorSchemeId; - } - - protected Group getGroup(PortletRequest portletRequest) throws Exception { - return ActionUtil.getGroup(portletRequest); - } - - protected byte[] getIconBytes( - UploadPortletRequest uploadPortletRequest, String iconFileName) { - - InputStream inputStream = null; - - try { - inputStream = uploadPortletRequest.getFileAsStream(iconFileName); - - if (inputStream != null) { - return FileUtil.getBytes(inputStream); - } - } - catch (IOException e) { - if (_log.isWarnEnabled()) { - _log.warn("Unable to retrieve icon", e); - } - } - - return new byte[0]; - } - - protected UnicodeProperties getThemeSettingsProperties( - ActionRequest actionRequest, long companyId, - UnicodeProperties typeSettingsProperties, String device, - String themeId, boolean wapTheme) - throws Exception { - - Theme theme = ThemeLocalServiceUtil.getTheme( - companyId, themeId, wapTheme); - - deleteThemeSettingsProperties(typeSettingsProperties, device); - - Map configurableSettings = - theme.getConfigurableSettings(); - - if (configurableSettings.isEmpty()) { - return typeSettingsProperties; - } - - for (String key : configurableSettings.keySet()) { - ThemeSetting themeSetting = configurableSettings.get(key); - - String type = GetterUtil.getString(themeSetting.getType(), "text"); - - String property = - device + "ThemeSettingsProperties--" + key + - StringPool.DOUBLE_DASH; - - String value = ParamUtil.getString(actionRequest, property); - - if (type.equals("checkbox")) { - value = String.valueOf(GetterUtil.getBoolean(value)); - } - - if (!value.equals(themeSetting.getValue())) { - typeSettingsProperties.setProperty( - ThemeSettingImpl.namespaceProperty(device, key), - value); - } - } - - return typeSettingsProperties; - } - - @Override - protected boolean isCheckMethodOnProcessAction() { - return _CHECK_METHOD_ON_PROCESS_ACTION; - } - - protected void selectLayoutBranch(ActionRequest actionRequest) - throws Exception { - - HttpServletRequest request = PortalUtil.getHttpServletRequest( - actionRequest); - - ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute( - WebKeys.THEME_DISPLAY); - - long layoutSetBranchId = ParamUtil.getLong( - actionRequest, "layoutSetBranchId"); - - long layoutBranchId = ParamUtil.getLong( - actionRequest, "layoutBranchId"); - - StagingUtil.setRecentLayoutBranchId( - request, layoutSetBranchId, themeDisplay.getPlid(), - layoutBranchId); - } - - protected void selectLayoutSetBranch(ActionRequest actionRequest) - throws Exception { - - HttpServletRequest request = PortalUtil.getHttpServletRequest( - actionRequest); - - long groupId = ParamUtil.getLong(actionRequest, "groupId"); - boolean privateLayout = ParamUtil.getBoolean( - actionRequest, "privateLayout"); - - LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet( - groupId, privateLayout); - - long layoutSetBranchId = ParamUtil.getLong( - actionRequest, "layoutSetBranchId"); - - // Ensure layout set branch exists - - LayoutSetBranch layoutSetBranch = - LayoutSetBranchLocalServiceUtil.getLayoutSetBranch( - layoutSetBranchId); - - StagingUtil.setRecentLayoutSetBranchId( - request, layoutSet.getLayoutSetId(), - layoutSetBranch.getLayoutSetBranchId()); - } - - protected String updateCloseRedirect( - String closeRedirect, Group group, Layout layout, - String oldLayoutFriendlyURL) { - - if (Validator.isNull(closeRedirect) || - Validator.isNull(oldLayoutFriendlyURL)) { - - return closeRedirect; - } - - if (layout != null) { - String oldPath = oldLayoutFriendlyURL; - String newPath = layout.getFriendlyURL(); - - return PortalUtil.updateRedirect(closeRedirect, oldPath, newPath); - } - else if (group != null) { - String oldPath = group.getFriendlyURL() + oldLayoutFriendlyURL; - String newPath = group.getFriendlyURL(); - - return PortalUtil.updateRedirect(closeRedirect, oldPath, newPath); - } - - return closeRedirect; - } - - protected void updateDisplayOrder(ActionRequest actionRequest) - throws Exception { - - long groupId = ParamUtil.getLong(actionRequest, "groupId"); - boolean privateLayout = ParamUtil.getBoolean( - actionRequest, "privateLayout"); - long parentLayoutId = ParamUtil.getLong( - actionRequest, "parentLayoutId"); - long[] layoutIds = StringUtil.split( - ParamUtil.getString(actionRequest, "layoutIds"), 0L); - - ServiceContext serviceContext = ServiceContextFactory.getInstance( - actionRequest); - - LayoutServiceUtil.setLayouts( - groupId, privateLayout, parentLayoutId, layoutIds, serviceContext); - } - - protected Object[] updateLayout( - ActionRequest actionRequest, ActionResponse actionResponse) - throws Exception { - - UploadPortletRequest uploadPortletRequest = - PortalUtil.getUploadPortletRequest(actionRequest); - - ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute( - WebKeys.THEME_DISPLAY); - - String cmd = ParamUtil.getString(uploadPortletRequest, Constants.CMD); - - long groupId = ParamUtil.getLong(actionRequest, "groupId"); - long liveGroupId = ParamUtil.getLong(actionRequest, "liveGroupId"); - long stagingGroupId = ParamUtil.getLong( - actionRequest, "stagingGroupId"); - boolean privateLayout = ParamUtil.getBoolean( - actionRequest, "privateLayout"); - long layoutId = ParamUtil.getLong(actionRequest, "layoutId"); - long parentLayoutId = ParamUtil.getLong( - uploadPortletRequest, "parentLayoutId"); - Map nameMap = LocalizationUtil.getLocalizationMap( - actionRequest, "name"); - Map titleMap = LocalizationUtil.getLocalizationMap( - actionRequest, "title"); - Map descriptionMap = - LocalizationUtil.getLocalizationMap(actionRequest, "description"); - Map keywordsMap = LocalizationUtil.getLocalizationMap( - actionRequest, "keywords"); - Map robotsMap = LocalizationUtil.getLocalizationMap( - actionRequest, "robots"); - String type = ParamUtil.getString(uploadPortletRequest, "type"); - boolean hidden = ParamUtil.getBoolean(uploadPortletRequest, "hidden"); - String friendlyURL = ParamUtil.getString( - uploadPortletRequest, "friendlyURL"); - boolean iconImage = ParamUtil.getBoolean( - uploadPortletRequest, "iconImage"); - byte[] iconBytes = getIconBytes(uploadPortletRequest, "iconFileName"); - long layoutPrototypeId = ParamUtil.getLong( - uploadPortletRequest, "layoutPrototypeId"); - - boolean inheritFromParentLayoutId = ParamUtil.getBoolean( - uploadPortletRequest, "inheritFromParentLayoutId"); - - long copyLayoutId = ParamUtil.getLong( - uploadPortletRequest, "copyLayoutId"); - - String layoutTemplateId = ParamUtil.getString( - uploadPortletRequest, "layoutTemplateId", - PropsValues.DEFAULT_LAYOUT_TEMPLATE_ID); - - ServiceContext serviceContext = ServiceContextFactory.getInstance( - Layout.class.getName(), actionRequest); - - Layout layout = null; - UnicodeProperties layoutTypeSettingsProperties = null; - String oldFriendlyURL = StringPool.BLANK; - - if (cmd.equals(Constants.ADD)) { - - // Add layout - - if (inheritFromParentLayoutId && (parentLayoutId > 0)) { - Layout parentLayout = LayoutLocalServiceUtil.getLayout( - groupId, privateLayout, parentLayoutId); - - layout = LayoutServiceUtil.addLayout( - groupId, privateLayout, parentLayoutId, nameMap, - titleMap, descriptionMap, keywordsMap, robotsMap, - parentLayout.getType(), hidden, friendlyURL, - serviceContext); - - LayoutServiceUtil.updateLayout( - layout.getGroupId(), layout.isPrivateLayout(), - layout.getLayoutId(), parentLayout.getTypeSettings()); - - if (parentLayout.isTypePortlet()) { - ActionUtil.copyPreferences( - actionRequest, layout, parentLayout); - - SitesUtil.copyLookAndFeel(layout, parentLayout); - } - } - else if (layoutPrototypeId > 0) { - LayoutPrototype layoutPrototype = - LayoutPrototypeServiceUtil.getLayoutPrototype( - layoutPrototypeId); - - serviceContext.setAttribute("layoutPrototypeLinkEnabled", true); - serviceContext.setAttribute( - "layoutPrototypeUuid", layoutPrototype.getUuid()); - - layout = LayoutServiceUtil.addLayout( - groupId, privateLayout, parentLayoutId, nameMap, - titleMap, descriptionMap, keywordsMap, robotsMap, - LayoutConstants.TYPE_PORTLET, hidden, friendlyURL, - serviceContext); - } - else { - layout = LayoutServiceUtil.addLayout( - groupId, privateLayout, parentLayoutId, nameMap, - titleMap, descriptionMap, keywordsMap, robotsMap, type, - hidden, friendlyURL, serviceContext); - } - - layoutTypeSettingsProperties = layout.getTypeSettingsProperties(); - } - else { - - // Update layout - - layout = LayoutLocalServiceUtil.getLayout( - groupId, privateLayout, layoutId); - - oldFriendlyURL = layout.getFriendlyURL(); - - layout = LayoutServiceUtil.updateLayout( - groupId, privateLayout, layoutId, layout.getParentLayoutId(), - nameMap, titleMap, descriptionMap, keywordsMap, robotsMap, - type, hidden, friendlyURL, Boolean.valueOf(iconImage), - iconBytes, serviceContext); - - layoutTypeSettingsProperties = layout.getTypeSettingsProperties(); - - if (oldFriendlyURL.equals(layout.getFriendlyURL())) { - oldFriendlyURL = StringPool.BLANK; - } - - UnicodeProperties formTypeSettingsProperties = - PropertiesParamUtil.getProperties( - actionRequest, "TypeSettingsProperties--"); - - if (type.equals(LayoutConstants.TYPE_PORTLET)) { - LayoutTypePortlet layoutTypePortlet = - (LayoutTypePortlet)layout.getLayoutType(); - - layoutTypePortlet.setLayoutTemplateId( - themeDisplay.getUserId(), layoutTemplateId); - - if ((copyLayoutId > 0) && - (copyLayoutId != layout.getLayoutId())) { - - try { - Layout copyLayout = LayoutLocalServiceUtil.getLayout( - groupId, privateLayout, copyLayoutId); - - if (copyLayout.isTypePortlet()) { - layoutTypeSettingsProperties = - copyLayout.getTypeSettingsProperties(); - - ActionUtil.copyPreferences( - actionRequest, layout, copyLayout); - - SitesUtil.copyLookAndFeel(layout, copyLayout); - } - } - catch (NoSuchLayoutException nsle) { - } - } - else { - layoutTypeSettingsProperties.putAll( - formTypeSettingsProperties); - - LayoutServiceUtil.updateLayout( - groupId, privateLayout, layoutId, - layout.getTypeSettings()); - } - } - else { - layout.setTypeSettingsProperties(formTypeSettingsProperties); - - layoutTypeSettingsProperties.putAll( - layout.getTypeSettingsProperties()); - - LayoutServiceUtil.updateLayout( - groupId, privateLayout, layoutId, layout.getTypeSettings()); - } - - HttpServletResponse response = PortalUtil.getHttpServletResponse( - actionResponse); - - LayoutSettings layoutSettings = LayoutSettings.getInstance(layout); - - EventsProcessorUtil.process( - PropsKeys.LAYOUT_CONFIGURATION_ACTION_UPDATE, - layoutSettings.getConfigurationActionUpdate(), - uploadPortletRequest, response); - } - - updateLookAndFeel( - actionRequest, themeDisplay.getCompanyId(), liveGroupId, - stagingGroupId, privateLayout, layout.getLayoutId(), - layoutTypeSettingsProperties); - - return new Object[] {layout, oldFriendlyURL}; - } - - protected void updateLayoutRevision( - ActionRequest actionRequest, ThemeDisplay themeDisplay) - throws Exception { - - long layoutRevisionId = ParamUtil.getLong( - actionRequest, "layoutRevisionId"); - - LayoutRevision layoutRevision = - LayoutRevisionLocalServiceUtil.getLayoutRevision(layoutRevisionId); - - ServiceContext serviceContext = ServiceContextFactory.getInstance( - actionRequest); - - LayoutRevision enableLayoutRevision = - LayoutRevisionLocalServiceUtil.updateLayoutRevision( - serviceContext.getUserId(), layoutRevisionId, - layoutRevision.getLayoutBranchId(), layoutRevision.getName(), - layoutRevision.getTitle(), layoutRevision.getDescription(), - layoutRevision.getKeywords(), layoutRevision.getRobots(), - layoutRevision.getTypeSettings(), layoutRevision.getIconImage(), - layoutRevision.getIconImageId(), layoutRevision.getThemeId(), - layoutRevision.getColorSchemeId(), layoutRevision.getWapThemeId(), - layoutRevision.getWapColorSchemeId(), layoutRevision.getCss(), - serviceContext); - - if (layoutRevision.getStatus() == WorkflowConstants.STATUS_INCOMPLETE) { - LayoutRevision lastLayoutRevision = - LayoutRevisionLocalServiceUtil.fetchLastLayoutRevision( - enableLayoutRevision.getPlid(), true); - - if (lastLayoutRevision != null) { - LayoutRevision newLayoutRevision = - LayoutRevisionLocalServiceUtil.addLayoutRevision( - serviceContext.getUserId(), - layoutRevision.getLayoutSetBranchId(), - layoutRevision.getLayoutBranchId(), - enableLayoutRevision.getLayoutRevisionId(), - false, layoutRevision.getPlid(), - lastLayoutRevision.getLayoutRevisionId(), - lastLayoutRevision.getPrivateLayout(), - lastLayoutRevision.getName(), - lastLayoutRevision.getTitle(), - lastLayoutRevision.getDescription(), - lastLayoutRevision.getKeywords(), - lastLayoutRevision.getRobots(), - lastLayoutRevision.getTypeSettings(), - lastLayoutRevision.isIconImage(), - lastLayoutRevision.getIconImageId(), - lastLayoutRevision.getThemeId(), - lastLayoutRevision.getColorSchemeId(), - lastLayoutRevision.getWapThemeId(), - lastLayoutRevision.getWapColorSchemeId(), - lastLayoutRevision.getCss(), serviceContext); - - StagingUtil.setRecentLayoutRevisionId( - themeDisplay.getUser(), - newLayoutRevision.getLayoutSetBranchId(), - newLayoutRevision.getPlid(), - newLayoutRevision.getLayoutRevisionId()); - } - } - } - - protected void updateLookAndFeel( - ActionRequest actionRequest, long companyId, long liveGroupId, - long stagingGroupId, boolean privateLayout, long layoutId, - UnicodeProperties typeSettingsProperties) - throws Exception { - - String[] devices = StringUtil.split( - ParamUtil.getString(actionRequest, "devices")); - - for (String device : devices) { - String themeId = ParamUtil.getString( - actionRequest, device + "ThemeId"); - String colorSchemeId = ParamUtil.getString( - actionRequest, device + "ColorSchemeId"); - String css = ParamUtil.getString(actionRequest, device + "Css"); - boolean wapTheme = device.equals("wap"); - - boolean inheritLookAndFeel = ParamUtil.getBoolean( - actionRequest, device + "InheritLookAndFeel"); - - if (inheritLookAndFeel) { - themeId = ThemeImpl.getDefaultRegularThemeId(companyId); - colorSchemeId = StringPool.BLANK; - - deleteThemeSettingsProperties(typeSettingsProperties, device); - } - else if (Validator.isNotNull(themeId)) { - colorSchemeId = getColorSchemeId( - companyId, themeId, colorSchemeId, wapTheme); - - getThemeSettingsProperties( - actionRequest, companyId, typeSettingsProperties, device, - themeId, wapTheme); - } - - long groupId = liveGroupId; - - if (stagingGroupId > 0) { - groupId = stagingGroupId; - } - - LayoutServiceUtil.updateLayout( - groupId, privateLayout, layoutId, - typeSettingsProperties.toString()); - - LayoutServiceUtil.updateLookAndFeel( - groupId, privateLayout, layoutId, themeId, colorSchemeId, css, - wapTheme); - } - } - - private static final boolean _CHECK_METHOD_ON_PROCESS_ACTION = false; - - private static Log _log = LogFactoryUtil.getLog(EditLayoutsAction.class); - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portlet.layoutsadmin.action; + +import com.liferay.portal.ImageTypeException; +import com.liferay.portal.LayoutFriendlyURLException; +import com.liferay.portal.LayoutHiddenException; +import com.liferay.portal.LayoutNameException; +import com.liferay.portal.LayoutParentLayoutIdException; +import com.liferay.portal.LayoutSetVirtualHostException; +import com.liferay.portal.LayoutTypeException; +import com.liferay.portal.NoSuchGroupException; +import com.liferay.portal.NoSuchLayoutException; +import com.liferay.portal.RemoteExportException; +import com.liferay.portal.RemoteOptionsException; +import com.liferay.portal.RequiredLayoutException; +import com.liferay.portal.events.EventsProcessorUtil; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.servlet.SessionErrors; +import com.liferay.portal.kernel.servlet.SessionMessages; +import com.liferay.portal.kernel.staging.StagingUtil; +import com.liferay.portal.kernel.upload.UploadException; +import com.liferay.portal.kernel.upload.UploadPortletRequest; +import com.liferay.portal.kernel.util.Constants; +import com.liferay.portal.kernel.util.FileUtil; +import com.liferay.portal.kernel.util.GetterUtil; +import com.liferay.portal.kernel.util.HttpUtil; +import com.liferay.portal.kernel.util.LocalizationUtil; +import com.liferay.portal.kernel.util.ParamUtil; +import com.liferay.portal.kernel.util.PropertiesParamUtil; +import com.liferay.portal.kernel.util.PropsKeys; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.UnicodeProperties; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.kernel.workflow.WorkflowConstants; +import com.liferay.portal.model.ColorScheme; +import com.liferay.portal.model.Group; +import com.liferay.portal.model.Layout; +import com.liferay.portal.model.LayoutConstants; +import com.liferay.portal.model.LayoutPrototype; +import com.liferay.portal.model.LayoutRevision; +import com.liferay.portal.model.LayoutSet; +import com.liferay.portal.model.LayoutSetBranch; +import com.liferay.portal.model.LayoutTypePortlet; +import com.liferay.portal.model.Theme; +import com.liferay.portal.model.ThemeSetting; +import com.liferay.portal.model.User; +import com.liferay.portal.model.impl.ThemeImpl; +import com.liferay.portal.model.impl.ThemeSettingImpl; +import com.liferay.portal.security.auth.PrincipalException; +import com.liferay.portal.security.permission.ActionKeys; +import com.liferay.portal.security.permission.PermissionChecker; +import com.liferay.portal.service.LayoutLocalServiceUtil; +import com.liferay.portal.service.LayoutPrototypeServiceUtil; +import com.liferay.portal.service.LayoutRevisionLocalServiceUtil; +import com.liferay.portal.service.LayoutServiceUtil; +import com.liferay.portal.service.LayoutSetBranchLocalServiceUtil; +import com.liferay.portal.service.LayoutSetLocalServiceUtil; +import com.liferay.portal.service.ServiceContext; +import com.liferay.portal.service.ServiceContextFactory; +import com.liferay.portal.service.ThemeLocalServiceUtil; +import com.liferay.portal.service.UserLocalServiceUtil; +import com.liferay.portal.service.permission.GroupPermissionUtil; +import com.liferay.portal.service.permission.LayoutPermissionUtil; +import com.liferay.portal.service.permission.LayoutPrototypePermissionUtil; +import com.liferay.portal.service.permission.LayoutSetPrototypePermissionUtil; +import com.liferay.portal.service.permission.OrganizationPermissionUtil; +import com.liferay.portal.service.permission.UserPermissionUtil; +import com.liferay.portal.struts.PortletAction; +import com.liferay.portal.theme.ThemeDisplay; +import com.liferay.portal.util.LayoutSettings; +import com.liferay.portal.util.PortalUtil; +import com.liferay.portal.util.PropsValues; +import com.liferay.portal.util.WebKeys; +import com.liferay.portlet.sites.action.ActionUtil; +import com.liferay.portlet.sites.util.SitesUtil; + +import java.io.IOException; +import java.io.InputStream; + +import java.util.Iterator; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import javax.portlet.ActionRequest; +import javax.portlet.ActionResponse; +import javax.portlet.PortletConfig; +import javax.portlet.PortletContext; +import javax.portlet.PortletRequest; +import javax.portlet.PortletRequestDispatcher; +import javax.portlet.RenderRequest; +import javax.portlet.RenderResponse; +import javax.portlet.ResourceRequest; +import javax.portlet.ResourceResponse; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.struts.action.ActionForm; +import org.apache.struts.action.ActionForward; +import org.apache.struts.action.ActionMapping; + +/** + * @author Brian Wing Shun Chan + * @author Julio Camarero + */ +public class EditLayoutsAction extends PortletAction { + + @Override + public void processAction( + ActionMapping mapping, ActionForm form, PortletConfig portletConfig, + ActionRequest actionRequest, ActionResponse actionResponse) + throws Exception { + + try { + checkPermissions(actionRequest); + } + catch (PrincipalException pe) { + return; + } + + ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute( + WebKeys.THEME_DISPLAY); + + String cmd = ParamUtil.getString(actionRequest, Constants.CMD); + + try { + String redirect = ParamUtil.getString(actionRequest, "redirect"); + String closeRedirect = ParamUtil.getString( + actionRequest, "closeRedirect"); + + Layout layout = null; + String oldFriendlyURL = StringPool.BLANK; + + if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) { + Object[] returnValue = updateLayout( + actionRequest, actionResponse); + + layout = (Layout)returnValue[0]; + oldFriendlyURL = (String)returnValue[1]; + + redirect = updateCloseRedirect( + redirect, null, layout, oldFriendlyURL); + closeRedirect = updateCloseRedirect( + closeRedirect, null, layout, oldFriendlyURL); + } + else if (cmd.equals(Constants.DELETE)) { + Object[] returnValue = SitesUtil.deleteLayout( + actionRequest, actionResponse); + + Group group = (Group)returnValue[0]; + oldFriendlyURL = (String)returnValue[1]; + long newRefererPlid = (Long)returnValue[2]; + + redirect = updateCloseRedirect( + redirect, group, null, oldFriendlyURL); + redirect = HttpUtil.setParameter( + redirect, "refererPlid", newRefererPlid); + + closeRedirect = updateCloseRedirect( + closeRedirect, group, null, oldFriendlyURL); + } + else if (cmd.equals("copy_from_live")) { + StagingUtil.copyFromLive(actionRequest); + } + else if (cmd.equals("display_order")) { + updateDisplayOrder(actionRequest); + } + else if (cmd.equals("delete_layout_revision")) { + deleteLayoutRevision(actionRequest); + } + else if (cmd.equals("enable")) { + enableLayout(actionRequest); + } + else if (cmd.equals("publish_to_live")) { + StagingUtil.publishToLive(actionRequest); + } + else if (cmd.equals("publish_to_remote")) { + StagingUtil.publishToRemote(actionRequest); + } + else if (cmd.equals("reset_customized_view")) { + LayoutTypePortlet layoutTypePortlet = + themeDisplay.getLayoutTypePortlet(); + + if ((layoutTypePortlet != null) && + layoutTypePortlet.isCustomizable() && + layoutTypePortlet.isCustomizedView()) { + + layoutTypePortlet.resetUserPreferences(); + } + } + else if (cmd.equals("reset_prototype")) { + SitesUtil.resetPrototype(themeDisplay.getLayout()); + } + else if (cmd.equals("schedule_copy_from_live")) { + StagingUtil.scheduleCopyFromLive(actionRequest); + } + else if (cmd.equals("schedule_publish_to_live")) { + StagingUtil.schedulePublishToLive(actionRequest); + } + else if (cmd.equals("schedule_publish_to_remote")) { + StagingUtil.schedulePublishToRemote(actionRequest); + } + else if (cmd.equals("select_layout_set_branch")) { + selectLayoutSetBranch(actionRequest); + } + else if (cmd.equals("select_layout_branch")) { + selectLayoutBranch(actionRequest); + } + else if (cmd.equals("unschedule_copy_from_live")) { + StagingUtil.unscheduleCopyFromLive(actionRequest); + } + else if (cmd.equals("unschedule_publish_to_live")) { + StagingUtil.unschedulePublishToLive(actionRequest); + } + else if (cmd.equals("unschedule_publish_to_remote")) { + StagingUtil.unschedulePublishToRemote(actionRequest); + } + else if (cmd.equals("update_layout_revision")) { + updateLayoutRevision(actionRequest, themeDisplay); + } + + if (Validator.isNotNull(closeRedirect)) { + SessionMessages.add( + actionRequest, + portletConfig.getPortletName() + + SessionMessages.KEY_SUFFIX_CLOSE_REDIRECT, + closeRedirect); + } + + sendRedirect(actionRequest, actionResponse, redirect); + } + catch (Exception e) { + if (e instanceof NoSuchLayoutException || + e instanceof PrincipalException) { + + SessionErrors.add(actionRequest, e.getClass().getName()); + + setForward(actionRequest, "portlet.layouts_admin.error"); + } + else if (e instanceof ImageTypeException || + e instanceof LayoutFriendlyURLException || + e instanceof LayoutHiddenException || + e instanceof LayoutNameException || + e instanceof LayoutParentLayoutIdException || + e instanceof LayoutSetVirtualHostException || + e instanceof LayoutTypeException || + e instanceof RequiredLayoutException || + e instanceof UploadException) { + + if (e instanceof LayoutFriendlyURLException) { + SessionErrors.add( + actionRequest, + LayoutFriendlyURLException.class.getName(), e); + } + else { + SessionErrors.add(actionRequest, e.getClass().getName(), e); + } + } + else if (e instanceof RemoteExportException || + e instanceof RemoteOptionsException || + e instanceof SystemException) { + + SessionErrors.add(actionRequest, e.getClass().getName(), e); + + String redirect = ParamUtil.getString( + actionRequest, "pagesRedirect"); + + sendRedirect(actionRequest, actionResponse, redirect); + } + else { + throw e; + } + } + } + + @Override + public ActionForward render( + ActionMapping mapping, ActionForm form, PortletConfig portletConfig, + RenderRequest renderRequest, RenderResponse renderResponse) + throws Exception { + + try { + checkPermissions(renderRequest); + } + catch (PrincipalException pe) { + SessionErrors.add( + renderRequest, PrincipalException.class.getName()); + + return mapping.findForward("portlet.layouts_admin.error"); + } + + try { + getGroup(renderRequest); + } + catch (Exception e) { + if (e instanceof NoSuchGroupException || + e instanceof PrincipalException) { + + SessionErrors.add(renderRequest, e.getClass().getName()); + + return mapping.findForward("portlet.layouts_admin.error"); + } + else { + throw e; + } + } + + return mapping.findForward( + getForward(renderRequest, "portlet.layouts_admin.edit_layouts")); + } + + @Override + public void serveResource( + ActionMapping mapping, ActionForm form, PortletConfig portletConfig, + ResourceRequest resourceRequest, ResourceResponse resourceResponse) + throws Exception { + + String cmd = ParamUtil.getString(resourceRequest, Constants.CMD); + + PortletContext portletContext = portletConfig.getPortletContext(); + + PortletRequestDispatcher portletRequestDispatcher = null; + + if (cmd.equals(ActionKeys.PUBLISH_STAGING)) { + portletRequestDispatcher = portletContext.getRequestDispatcher( + "/html/portlet/layouts_admin/scheduled_publishing_events.jsp"); + } + else if (cmd.equals(ActionKeys.VIEW_TREE)) { + getGroup(resourceRequest); + + portletRequestDispatcher = portletContext.getRequestDispatcher( + "/html/portlet/layouts_admin/tree_js.jsp"); + } + else { + getGroup(resourceRequest); + + portletRequestDispatcher = portletContext.getRequestDispatcher( + "/html/portlet/layouts_admin/view_resources.jsp"); + } + + portletRequestDispatcher.include(resourceRequest, resourceResponse); + } + + protected void checkPermissions(PortletRequest portletRequest) + throws Exception { + + // LEP-850 + + Group group = getGroup(portletRequest); + + if (group == null) { + throw new PrincipalException(); + } + + ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute( + WebKeys.THEME_DISPLAY); + + PermissionChecker permissionChecker = + themeDisplay.getPermissionChecker(); + + Layout layout = themeDisplay.getLayout(); + + String cmd = ParamUtil.getString(portletRequest, Constants.CMD); + + long selPlid = ParamUtil.getLong(portletRequest, "selPlid"); + + if (selPlid > 0) { + layout = LayoutLocalServiceUtil.getLayout(selPlid); + } + + if (cmd.equals(Constants.ADD)) { + long parentPlid = ParamUtil.getLong(portletRequest, "parentPlid"); + + if ((parentPlid == LayoutConstants.DEFAULT_PARENT_LAYOUT_ID)) { + if (!GroupPermissionUtil.contains( + permissionChecker, group.getGroupId(), + ActionKeys.ADD_LAYOUT)) { + + throw new PrincipalException(); + } + else { + return; + } + } + else { + layout = LayoutLocalServiceUtil.getLayout(parentPlid); + + if (!LayoutPermissionUtil.contains( + permissionChecker, layout, ActionKeys.ADD_LAYOUT)) { + + throw new PrincipalException(); + } + else { + return; + } + } + } + else if (cmd.equals(Constants.DELETE)) { + if (!LayoutPermissionUtil.contains( + permissionChecker, layout, ActionKeys.DELETE)) { + + throw new PrincipalException(); + } + else { + return; + } + } + else if (cmd.equals("reset_customized_view")) { + if (!LayoutPermissionUtil.contains( + permissionChecker, layout, ActionKeys.CUSTOMIZE)) { + + throw new PrincipalException(); + } + else { + return; + } + } + else if (cmd.equals("reset_prototype")) { + if (!LayoutPermissionUtil.contains( + permissionChecker, layout, ActionKeys.UPDATE) || + !GroupPermissionUtil.contains( + permissionChecker, layout.getGroupId(), + ActionKeys.UPDATE)) { + + throw new PrincipalException(); + } + else { + return; + } + } + + boolean hasUpdateLayoutPermission = false; + + if (layout != null) { + hasUpdateLayoutPermission = LayoutPermissionUtil.contains( + permissionChecker, layout, ActionKeys.UPDATE); + } + + boolean hasPermission = true; + + if (cmd.equals("publish_to_live")) { + if (group.isSite()) { + boolean publishToLive = GroupPermissionUtil.contains( + permissionChecker, group.getGroupId(), + ActionKeys.PUBLISH_STAGING); + + if (!hasUpdateLayoutPermission && !publishToLive) { + hasPermission = false; + } + } + else if (group.isOrganization()) { + boolean publishToLive = OrganizationPermissionUtil.contains( + permissionChecker, group.getOrganizationId(), + ActionKeys.PUBLISH_STAGING); + + if (!hasUpdateLayoutPermission && !publishToLive) { + hasPermission = false; + } + } + } + + if (group.isCompany()) { + if (!permissionChecker.isCompanyAdmin()) { + hasPermission = false; + } + } + else if (group.isLayoutPrototype()) { + LayoutPrototypePermissionUtil.check( + permissionChecker, group.getClassPK(), ActionKeys.UPDATE); + } + else if (group.isLayoutSetPrototype()) { + LayoutSetPrototypePermissionUtil.check( + permissionChecker, group.getClassPK(), ActionKeys.UPDATE); + } + else if (group.isUser()) { + long groupUserId = group.getClassPK(); + + User groupUser = UserLocalServiceUtil.getUserById(groupUserId); + + long[] organizationIds = groupUser.getOrganizationIds(); + + UserPermissionUtil.check( + permissionChecker, groupUserId, organizationIds, + ActionKeys.UPDATE); + } + + if (!hasPermission) { + throw new PrincipalException(); + } + } + + protected void deleteLayoutRevision(ActionRequest actionRequest) + throws Exception { + + HttpServletRequest request = PortalUtil.getHttpServletRequest( + actionRequest); + + long layoutRevisionId = ParamUtil.getLong( + actionRequest, "layoutRevisionId"); + + LayoutRevision layoutRevision = + LayoutRevisionLocalServiceUtil.getLayoutRevision(layoutRevisionId); + + LayoutRevisionLocalServiceUtil.deleteLayoutRevision(layoutRevision); + + boolean updateRecentLayoutRevisionId = ParamUtil.getBoolean( + actionRequest, "updateRecentLayoutRevisionId"); + + if (updateRecentLayoutRevisionId) { + StagingUtil.setRecentLayoutRevisionId( + request, layoutRevision.getLayoutSetBranchId(), + layoutRevision.getPlid(), + layoutRevision.getParentLayoutRevisionId()); + } + } + + protected void deleteThemeSettingsProperties( + UnicodeProperties typeSettingsProperties, String device) { + + String keyPrefix = ThemeSettingImpl.namespaceProperty(device); + + Set keys = typeSettingsProperties.keySet(); + + Iterator itr = keys.iterator(); + + while (itr.hasNext()) { + String key = itr.next(); + + if (key.startsWith(keyPrefix)) { + itr.remove(); + } + } + } + + protected void enableLayout(ActionRequest actionRequest) throws Exception { + long incompleteLayoutRevisionId = ParamUtil.getLong( + actionRequest, "incompleteLayoutRevisionId"); + + LayoutRevision incompleteLayoutRevision = + LayoutRevisionLocalServiceUtil.getLayoutRevision( + incompleteLayoutRevisionId); + + long layoutBranchId = ParamUtil.getLong( + actionRequest, "layoutBranchId", + incompleteLayoutRevision.getLayoutBranchId()); + + ServiceContext serviceContext = ServiceContextFactory.getInstance( + actionRequest); + + serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT); + + LayoutRevisionLocalServiceUtil.updateLayoutRevision( + serviceContext.getUserId(), + incompleteLayoutRevision.getLayoutRevisionId(), layoutBranchId, + incompleteLayoutRevision.getName(), + incompleteLayoutRevision.getTitle(), + incompleteLayoutRevision.getDescription(), + incompleteLayoutRevision.getKeywords(), + incompleteLayoutRevision.getRobots(), + incompleteLayoutRevision.getTypeSettings(), + incompleteLayoutRevision.getIconImage(), + incompleteLayoutRevision.getIconImageId(), + incompleteLayoutRevision.getThemeId(), + incompleteLayoutRevision.getColorSchemeId(), + incompleteLayoutRevision.getWapThemeId(), + incompleteLayoutRevision.getWapColorSchemeId(), + incompleteLayoutRevision.getCss(), serviceContext); + } + + protected String getColorSchemeId( + long companyId, String themeId, String colorSchemeId, + boolean wapTheme) + throws Exception { + + Theme theme = ThemeLocalServiceUtil.getTheme( + companyId, themeId, wapTheme); + + if (!theme.hasColorSchemes()) { + colorSchemeId = StringPool.BLANK; + } + + if (Validator.isNull(colorSchemeId)) { + ColorScheme colorScheme = ThemeLocalServiceUtil.getColorScheme( + companyId, themeId, colorSchemeId, wapTheme); + + colorSchemeId = colorScheme.getColorSchemeId(); + } + + return colorSchemeId; + } + + protected Group getGroup(PortletRequest portletRequest) throws Exception { + return ActionUtil.getGroup(portletRequest); + } + + protected byte[] getIconBytes( + UploadPortletRequest uploadPortletRequest, String iconFileName) { + + InputStream inputStream = null; + + try { + inputStream = uploadPortletRequest.getFileAsStream(iconFileName); + + if (inputStream != null) { + return FileUtil.getBytes(inputStream); + } + } + catch (IOException e) { + if (_log.isWarnEnabled()) { + _log.warn("Unable to retrieve icon", e); + } + } + + return new byte[0]; + } + + protected UnicodeProperties getThemeSettingsProperties( + ActionRequest actionRequest, long companyId, + UnicodeProperties typeSettingsProperties, String device, + String themeId, boolean wapTheme) + throws Exception { + + Theme theme = ThemeLocalServiceUtil.getTheme( + companyId, themeId, wapTheme); + + deleteThemeSettingsProperties(typeSettingsProperties, device); + + Map configurableSettings = + theme.getConfigurableSettings(); + + if (configurableSettings.isEmpty()) { + return typeSettingsProperties; + } + + for (String key : configurableSettings.keySet()) { + ThemeSetting themeSetting = configurableSettings.get(key); + + String type = GetterUtil.getString(themeSetting.getType(), "text"); + + String property = + device + "ThemeSettingsProperties--" + key + + StringPool.DOUBLE_DASH; + + String value = ParamUtil.getString(actionRequest, property); + + if (type.equals("checkbox")) { + value = String.valueOf(GetterUtil.getBoolean(value)); + } + + if (!value.equals(themeSetting.getValue())) { + typeSettingsProperties.setProperty( + ThemeSettingImpl.namespaceProperty(device, key), value); + } + } + + return typeSettingsProperties; + } + + @Override + protected boolean isCheckMethodOnProcessAction() { + return _CHECK_METHOD_ON_PROCESS_ACTION; + } + + protected void selectLayoutBranch(ActionRequest actionRequest) + throws Exception { + + HttpServletRequest request = PortalUtil.getHttpServletRequest( + actionRequest); + + ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute( + WebKeys.THEME_DISPLAY); + + long layoutSetBranchId = ParamUtil.getLong( + actionRequest, "layoutSetBranchId"); + + long layoutBranchId = ParamUtil.getLong( + actionRequest, "layoutBranchId"); + + StagingUtil.setRecentLayoutBranchId( + request, layoutSetBranchId, themeDisplay.getPlid(), layoutBranchId); + } + + protected void selectLayoutSetBranch(ActionRequest actionRequest) + throws Exception { + + HttpServletRequest request = PortalUtil.getHttpServletRequest( + actionRequest); + + long groupId = ParamUtil.getLong(actionRequest, "groupId"); + boolean privateLayout = ParamUtil.getBoolean( + actionRequest, "privateLayout"); + + LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet( + groupId, privateLayout); + + long layoutSetBranchId = ParamUtil.getLong( + actionRequest, "layoutSetBranchId"); + + // Ensure layout set branch exists + + LayoutSetBranch layoutSetBranch = + LayoutSetBranchLocalServiceUtil.getLayoutSetBranch( + layoutSetBranchId); + + StagingUtil.setRecentLayoutSetBranchId( + request, layoutSet.getLayoutSetId(), + layoutSetBranch.getLayoutSetBranchId()); + } + + protected String updateCloseRedirect( + String closeRedirect, Group group, Layout layout, + String oldLayoutFriendlyURL) { + + if (Validator.isNull(closeRedirect) || + Validator.isNull(oldLayoutFriendlyURL)) { + + return closeRedirect; + } + + if (layout != null) { + String oldPath = oldLayoutFriendlyURL; + String newPath = layout.getFriendlyURL(); + + return PortalUtil.updateRedirect(closeRedirect, oldPath, newPath); + } + else if (group != null) { + String oldPath = group.getFriendlyURL() + oldLayoutFriendlyURL; + String newPath = group.getFriendlyURL(); + + return PortalUtil.updateRedirect(closeRedirect, oldPath, newPath); + } + + return closeRedirect; + } + + protected void updateDisplayOrder(ActionRequest actionRequest) + throws Exception { + + long groupId = ParamUtil.getLong(actionRequest, "groupId"); + boolean privateLayout = ParamUtil.getBoolean( + actionRequest, "privateLayout"); + long parentLayoutId = ParamUtil.getLong( + actionRequest, "parentLayoutId"); + long[] layoutIds = StringUtil.split( + ParamUtil.getString(actionRequest, "layoutIds"), 0L); + + ServiceContext serviceContext = ServiceContextFactory.getInstance( + actionRequest); + + LayoutServiceUtil.setLayouts( + groupId, privateLayout, parentLayoutId, layoutIds, serviceContext); + } + + protected Object[] updateLayout( + ActionRequest actionRequest, ActionResponse actionResponse) + throws Exception { + + UploadPortletRequest uploadPortletRequest = + PortalUtil.getUploadPortletRequest(actionRequest); + + ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute( + WebKeys.THEME_DISPLAY); + + String cmd = ParamUtil.getString(uploadPortletRequest, Constants.CMD); + + long groupId = ParamUtil.getLong(actionRequest, "groupId"); + long liveGroupId = ParamUtil.getLong(actionRequest, "liveGroupId"); + long stagingGroupId = ParamUtil.getLong( + actionRequest, "stagingGroupId"); + boolean privateLayout = ParamUtil.getBoolean( + actionRequest, "privateLayout"); + long layoutId = ParamUtil.getLong(actionRequest, "layoutId"); + long parentLayoutId = ParamUtil.getLong( + uploadPortletRequest, "parentLayoutId"); + Map nameMap = LocalizationUtil.getLocalizationMap( + actionRequest, "name"); + Map titleMap = LocalizationUtil.getLocalizationMap( + actionRequest, "title"); + Map descriptionMap = + LocalizationUtil.getLocalizationMap(actionRequest, "description"); + Map keywordsMap = LocalizationUtil.getLocalizationMap( + actionRequest, "keywords"); + Map robotsMap = LocalizationUtil.getLocalizationMap( + actionRequest, "robots"); + String type = ParamUtil.getString(uploadPortletRequest, "type"); + boolean hidden = ParamUtil.getBoolean(uploadPortletRequest, "hidden"); + String friendlyURL = ParamUtil.getString( + uploadPortletRequest, "friendlyURL"); + boolean iconImage = ParamUtil.getBoolean( + uploadPortletRequest, "iconImage"); + byte[] iconBytes = getIconBytes(uploadPortletRequest, "iconFileName"); + long layoutPrototypeId = ParamUtil.getLong( + uploadPortletRequest, "layoutPrototypeId"); + + boolean inheritFromParentLayoutId = ParamUtil.getBoolean( + uploadPortletRequest, "inheritFromParentLayoutId"); + + long copyLayoutId = ParamUtil.getLong( + uploadPortletRequest, "copyLayoutId"); + + String layoutTemplateId = ParamUtil.getString( + uploadPortletRequest, "layoutTemplateId", + PropsValues.DEFAULT_LAYOUT_TEMPLATE_ID); + + ServiceContext serviceContext = ServiceContextFactory.getInstance( + Layout.class.getName(), actionRequest); + + Layout layout = null; + UnicodeProperties layoutTypeSettingsProperties = null; + String oldFriendlyURL = StringPool.BLANK; + + if (cmd.equals(Constants.ADD)) { + + // Add layout + + if (inheritFromParentLayoutId && (parentLayoutId > 0)) { + Layout parentLayout = LayoutLocalServiceUtil.getLayout( + groupId, privateLayout, parentLayoutId); + + layout = LayoutServiceUtil.addLayout( + groupId, privateLayout, parentLayoutId, nameMap, titleMap, + descriptionMap, keywordsMap, robotsMap, + parentLayout.getType(), hidden, friendlyURL, + serviceContext); + + LayoutServiceUtil.updateLayout( + layout.getGroupId(), layout.isPrivateLayout(), + layout.getLayoutId(), parentLayout.getTypeSettings()); + + if (parentLayout.isTypePortlet()) { + ActionUtil.copyPreferences( + actionRequest, layout, parentLayout); + + SitesUtil.copyLookAndFeel(layout, parentLayout); + } + } + else if (layoutPrototypeId > 0) { + LayoutPrototype layoutPrototype = + LayoutPrototypeServiceUtil.getLayoutPrototype( + layoutPrototypeId); + + serviceContext.setAttribute("layoutPrototypeLinkEnabled", true); + serviceContext.setAttribute( + "layoutPrototypeUuid", layoutPrototype.getUuid()); + + layout = LayoutServiceUtil.addLayout( + groupId, privateLayout, parentLayoutId, nameMap, titleMap, + descriptionMap, keywordsMap, robotsMap, + LayoutConstants.TYPE_PORTLET, hidden, friendlyURL, + serviceContext); + } + else { + layout = LayoutServiceUtil.addLayout( + groupId, privateLayout, parentLayoutId, nameMap, titleMap, + descriptionMap, keywordsMap, robotsMap, type, hidden, + friendlyURL, serviceContext); + } + + layoutTypeSettingsProperties = layout.getTypeSettingsProperties(); + } + else { + + // Update layout + + layout = LayoutLocalServiceUtil.getLayout( + groupId, privateLayout, layoutId); + + oldFriendlyURL = layout.getFriendlyURL(); + + layout = LayoutServiceUtil.updateLayout( + groupId, privateLayout, layoutId, layout.getParentLayoutId(), + nameMap, titleMap, descriptionMap, keywordsMap, robotsMap, type, + hidden, friendlyURL, Boolean.valueOf(iconImage), iconBytes, + serviceContext); + + layoutTypeSettingsProperties = layout.getTypeSettingsProperties(); + + if (oldFriendlyURL.equals(layout.getFriendlyURL())) { + oldFriendlyURL = StringPool.BLANK; + } + + UnicodeProperties formTypeSettingsProperties = + PropertiesParamUtil.getProperties( + actionRequest, "TypeSettingsProperties--"); + + if (type.equals(LayoutConstants.TYPE_PORTLET)) { + LayoutTypePortlet layoutTypePortlet = + (LayoutTypePortlet)layout.getLayoutType(); + + layoutTypePortlet.setLayoutTemplateId( + themeDisplay.getUserId(), layoutTemplateId); + + if ((copyLayoutId > 0) && + (copyLayoutId != layout.getLayoutId())) { + + try { + Layout copyLayout = LayoutLocalServiceUtil.getLayout( + groupId, privateLayout, copyLayoutId); + + if (copyLayout.isTypePortlet()) { + layoutTypeSettingsProperties = + copyLayout.getTypeSettingsProperties(); + + ActionUtil.copyPreferences( + actionRequest, layout, copyLayout); + + SitesUtil.copyLookAndFeel(layout, copyLayout); + } + } + catch (NoSuchLayoutException nsle) { + } + } + else { + layoutTypeSettingsProperties.putAll( + formTypeSettingsProperties); + + LayoutServiceUtil.updateLayout( + groupId, privateLayout, layoutId, + layout.getTypeSettings()); + } + } + else { + layout.setTypeSettingsProperties(formTypeSettingsProperties); + + layoutTypeSettingsProperties.putAll( + layout.getTypeSettingsProperties()); + + LayoutServiceUtil.updateLayout( + groupId, privateLayout, layoutId, layout.getTypeSettings()); + } + + HttpServletResponse response = PortalUtil.getHttpServletResponse( + actionResponse); + + LayoutSettings layoutSettings = LayoutSettings.getInstance(layout); + + EventsProcessorUtil.process( + PropsKeys.LAYOUT_CONFIGURATION_ACTION_UPDATE, + layoutSettings.getConfigurationActionUpdate(), + uploadPortletRequest, response); + } + + updateLookAndFeel( + actionRequest, themeDisplay.getCompanyId(), liveGroupId, + stagingGroupId, privateLayout, layout.getLayoutId(), + layoutTypeSettingsProperties); + + return new Object[] {layout, oldFriendlyURL}; + } + + protected void updateLayoutRevision( + ActionRequest actionRequest, ThemeDisplay themeDisplay) + throws Exception { + + long layoutRevisionId = ParamUtil.getLong( + actionRequest, "layoutRevisionId"); + + LayoutRevision layoutRevision = + LayoutRevisionLocalServiceUtil.getLayoutRevision(layoutRevisionId); + + ServiceContext serviceContext = ServiceContextFactory.getInstance( + actionRequest); + + LayoutRevision enableLayoutRevision = + LayoutRevisionLocalServiceUtil.updateLayoutRevision( + serviceContext.getUserId(), layoutRevisionId, + layoutRevision.getLayoutBranchId(), layoutRevision.getName(), + layoutRevision.getTitle(), layoutRevision.getDescription(), + layoutRevision.getKeywords(), layoutRevision.getRobots(), + layoutRevision.getTypeSettings(), layoutRevision.getIconImage(), + layoutRevision.getIconImageId(), layoutRevision.getThemeId(), + layoutRevision.getColorSchemeId(), layoutRevision.getWapThemeId(), + layoutRevision.getWapColorSchemeId(), layoutRevision.getCss(), + serviceContext); + + if (layoutRevision.getStatus() == WorkflowConstants.STATUS_INCOMPLETE) { + LayoutRevision lastLayoutRevision = + LayoutRevisionLocalServiceUtil.fetchLastLayoutRevision( + enableLayoutRevision.getPlid(), true); + + if (lastLayoutRevision != null) { + LayoutRevision newLayoutRevision = + LayoutRevisionLocalServiceUtil.addLayoutRevision( + serviceContext.getUserId(), + layoutRevision.getLayoutSetBranchId(), + layoutRevision.getLayoutBranchId(), + enableLayoutRevision.getLayoutRevisionId(), false, + layoutRevision.getPlid(), + lastLayoutRevision.getLayoutRevisionId(), + lastLayoutRevision.getPrivateLayout(), + lastLayoutRevision.getName(), + lastLayoutRevision.getTitle(), + lastLayoutRevision.getDescription(), + lastLayoutRevision.getKeywords(), + lastLayoutRevision.getRobots(), + lastLayoutRevision.getTypeSettings(), + lastLayoutRevision.isIconImage(), + lastLayoutRevision.getIconImageId(), + lastLayoutRevision.getThemeId(), + lastLayoutRevision.getColorSchemeId(), + lastLayoutRevision.getWapThemeId(), + lastLayoutRevision.getWapColorSchemeId(), + lastLayoutRevision.getCss(), serviceContext); + + StagingUtil.setRecentLayoutRevisionId( + themeDisplay.getUser(), + newLayoutRevision.getLayoutSetBranchId(), + newLayoutRevision.getPlid(), + newLayoutRevision.getLayoutRevisionId()); + } + } + } + + protected void updateLookAndFeel( + ActionRequest actionRequest, long companyId, long liveGroupId, + long stagingGroupId, boolean privateLayout, long layoutId, + UnicodeProperties typeSettingsProperties) + throws Exception { + + String[] devices = StringUtil.split( + ParamUtil.getString(actionRequest, "devices")); + + for (String device : devices) { + String themeId = ParamUtil.getString( + actionRequest, device + "ThemeId"); + String colorSchemeId = ParamUtil.getString( + actionRequest, device + "ColorSchemeId"); + String css = ParamUtil.getString(actionRequest, device + "Css"); + boolean wapTheme = device.equals("wap"); + + boolean inheritLookAndFeel = ParamUtil.getBoolean( + actionRequest, device + "InheritLookAndFeel"); + + if (inheritLookAndFeel) { + themeId = ThemeImpl.getDefaultRegularThemeId(companyId); + colorSchemeId = StringPool.BLANK; + + deleteThemeSettingsProperties(typeSettingsProperties, device); + } + else if (Validator.isNotNull(themeId)) { + colorSchemeId = getColorSchemeId( + companyId, themeId, colorSchemeId, wapTheme); + + getThemeSettingsProperties( + actionRequest, companyId, typeSettingsProperties, device, + themeId, wapTheme); + } + + long groupId = liveGroupId; + + if (stagingGroupId > 0) { + groupId = stagingGroupId; + } + + LayoutServiceUtil.updateLayout( + groupId, privateLayout, layoutId, + typeSettingsProperties.toString()); + + LayoutServiceUtil.updateLookAndFeel( + groupId, privateLayout, layoutId, themeId, colorSchemeId, css, + wapTheme); + } + } + + private static final boolean _CHECK_METHOD_ON_PROCESS_ACTION = false; + + private static Log _log = LogFactoryUtil.getLog(EditLayoutsAction.class); + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portlet/layoutsadmin/util/SitemapImpl.java b/portal-impl/src/com/liferay/portlet/layoutsadmin/util/SitemapImpl.java index e4992a92b84a83..79f73f310c5154 100644 --- a/portal-impl/src/com/liferay/portlet/layoutsadmin/util/SitemapImpl.java +++ b/portal-impl/src/com/liferay/portlet/layoutsadmin/util/SitemapImpl.java @@ -177,8 +177,7 @@ protected void visitLayout( if (layout.isHidden() || !PortalUtil.isLayoutSitemapable(layout) || !GetterUtil.getBoolean( - typeSettingsProperties.getProperty("sitemap-include"), - true)) { + typeSettingsProperties.getProperty("sitemap-include"), true)) { return; } diff --git a/portal-impl/src/com/liferay/portlet/login/action/FacebookConnectAction.java b/portal-impl/src/com/liferay/portlet/login/action/FacebookConnectAction.java index acefe1679e9be7..20e55f668c1209 100644 --- a/portal-impl/src/com/liferay/portlet/login/action/FacebookConnectAction.java +++ b/portal-impl/src/com/liferay/portlet/login/action/FacebookConnectAction.java @@ -260,8 +260,8 @@ protected void updateUser(User user, JSONObject jsonObject) UserLocalServiceUtil.updateUser( user.getUserId(), StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, false, user.getReminderQueryQuestion(), - user.getReminderQueryAnswer(), user.getScreenName(), - emailAddress, facebookId, user.getOpenId(), user.getLanguageId(), + user.getReminderQueryAnswer(), user.getScreenName(), emailAddress, + facebookId, user.getOpenId(), user.getLanguageId(), user.getTimeZoneId(), user.getGreeting(), user.getComments(), firstName, user.getMiddleName(), lastName, contact.getPrefixId(), contact.getSuffixId(), male, birthdayMonth, birthdayDay, diff --git a/portal-impl/src/com/liferay/portlet/messageboards/service/impl/MBMessageLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/messageboards/service/impl/MBMessageLocalServiceImpl.java index f4a002720b2761..e77c36cdd32b94 100644 --- a/portal-impl/src/com/liferay/portlet/messageboards/service/impl/MBMessageLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/messageboards/service/impl/MBMessageLocalServiceImpl.java @@ -173,9 +173,8 @@ public MBMessage addDiscussionMessage( MBMessage message = addMessage( userId, userName, groupId, categoryId, threadId, parentMessageId, - subject, body, MBMessageConstants.DEFAULT_FORMAT, - inputStreamOVPs, anonymous, priority, allowPingbacks, - serviceContext); + subject, body, MBMessageConstants.DEFAULT_FORMAT, inputStreamOVPs, + anonymous, priority, allowPingbacks, serviceContext); // Discussion @@ -451,8 +450,8 @@ public void addMessageResources( resourceLocalService.addResources( message.getCompanyId(), message.getGroupId(), message.getUserId(), - MBMessage.class.getName(), message.getMessageId(), - false, addGroupPermissions, addGuestPermissions); + MBMessage.class.getName(), message.getMessageId(), false, + addGroupPermissions, addGuestPermissions); } public void addMessageResources( @@ -1078,8 +1077,8 @@ public MBMessageDisplay getMessageDisplay( } return new MBMessageDisplayImpl( - message, parentMessage, category, thread, - previousThread, nextThread, status, threadView, this); + message, parentMessage, category, thread, previousThread, + nextThread, status, threadView, this); } public List getMessages( @@ -1300,8 +1299,8 @@ public void updateAsset( throws PortalException, SystemException { updateAsset( - userId, message, assetCategoryIds, assetTagNames, - assetLinkEntryIds, true); + userId, message, assetCategoryIds, assetTagNames, assetLinkEntryIds, + true); } public MBMessage updateDiscussionMessage( diff --git a/portal-impl/src/com/liferay/portlet/messageboards/service/impl/MBMessageServiceImpl.java b/portal-impl/src/com/liferay/portlet/messageboards/service/impl/MBMessageServiceImpl.java index 40a3f75eded36b..8aea86f0937dbd 100644 --- a/portal-impl/src/com/liferay/portlet/messageboards/service/impl/MBMessageServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/messageboards/service/impl/MBMessageServiceImpl.java @@ -128,8 +128,8 @@ public MBMessage addMessage( return mbMessageLocalService.addMessage( getGuestOrUserId(), null, groupId, categoryId, threadId, - parentMessageId, subject, body, format, inputStreamOVPs, - anonymous, priority, allowPingbacks, serviceContext); + parentMessageId, subject, body, format, inputStreamOVPs, anonymous, + priority, allowPingbacks, serviceContext); } public MBMessage addMessage( diff --git a/portal-impl/src/com/liferay/portlet/nestedportlets/action/ConfigurationActionImpl.java b/portal-impl/src/com/liferay/portlet/nestedportlets/action/ConfigurationActionImpl.java index 4fb30faef3eb9d..cec389a959dce3 100644 --- a/portal-impl/src/com/liferay/portlet/nestedportlets/action/ConfigurationActionImpl.java +++ b/portal-impl/src/com/liferay/portlet/nestedportlets/action/ConfigurationActionImpl.java @@ -131,8 +131,8 @@ protected void reorganizeNestedColumns( layoutTypePortlet.setStateMax(StringPool.BLANK); LayoutLocalServiceUtil.updateLayout( - layout.getGroupId(), layout.isPrivateLayout(), - layout.getLayoutId(), layout.getTypeSettings()); + layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), + layout.getTypeSettings()); } private static Pattern _pattern = Pattern.compile( diff --git a/portal-impl/src/com/liferay/portlet/polls/action/ViewChartAction.java b/portal-impl/src/com/liferay/portlet/polls/action/ViewChartAction.java index b157b3c1e13eb7..c509177cb34186 100644 --- a/portal-impl/src/com/liferay/portlet/polls/action/ViewChartAction.java +++ b/portal-impl/src/com/liferay/portlet/polls/action/ViewChartAction.java @@ -68,8 +68,8 @@ public ActionForward execute( if (chartType.equals("area")) { chart = ChartFactory.createAreaChart( - chartName, xName, yName, dataset, - PlotOrientation.VERTICAL, true, false, false); + chartName, xName, yName, dataset, PlotOrientation.VERTICAL, + true, false, false); } else if (chartType.equals("horizontal_bar")) { chart = ChartFactory.createBarChart( @@ -78,13 +78,13 @@ else if (chartType.equals("horizontal_bar")) { } else if (chartType.equals("line")) { chart = ChartFactory.createLineChart( - chartName, xName, yName, dataset, - PlotOrientation.VERTICAL, true, false, false); + chartName, xName, yName, dataset, PlotOrientation.VERTICAL, + true, false, false); } else if (chartType.equals("vertical_bar")) { chart = ChartFactory.createBarChart( - chartName, xName, yName, dataset, - PlotOrientation.VERTICAL, true, false, false); + chartName, xName, yName, dataset, PlotOrientation.VERTICAL, + true, false, false); } else { PieDataset pieData = DatasetUtilities.createPieDatasetForRow( diff --git a/portal-impl/src/com/liferay/portlet/polls/lar/PollsPortletDataHandlerImpl.java b/portal-impl/src/com/liferay/portlet/polls/lar/PollsPortletDataHandlerImpl.java index db301349ba148c..97222549afa6ff 100644 --- a/portal-impl/src/com/liferay/portlet/polls/lar/PollsPortletDataHandlerImpl.java +++ b/portal-impl/src/com/liferay/portlet/polls/lar/PollsPortletDataHandlerImpl.java @@ -208,8 +208,8 @@ protected static void importChoice( } else { importedChoice = PollsChoiceLocalServiceUtil.updateChoice( - existingChoice.getChoiceId(), questionId, - choice.getName(), choice.getDescription()); + existingChoice.getChoiceId(), questionId, choice.getName(), + choice.getDescription()); } } else { diff --git a/portal-impl/src/com/liferay/portlet/portalsettings/action/EditLDAPServerAction.java b/portal-impl/src/com/liferay/portlet/portalsettings/action/EditLDAPServerAction.java index 310d7b36f2f9e2..87ca89a11be237 100644 --- a/portal-impl/src/com/liferay/portlet/portalsettings/action/EditLDAPServerAction.java +++ b/portal-impl/src/com/liferay/portlet/portalsettings/action/EditLDAPServerAction.java @@ -197,20 +197,15 @@ protected void updateLDAPServer(ActionRequest actionRequest) } private static final String[] _KEYS = { - PropsKeys.LDAP_AUTH_SEARCH_FILTER, - PropsKeys.LDAP_BASE_DN, + PropsKeys.LDAP_AUTH_SEARCH_FILTER, PropsKeys.LDAP_BASE_DN, PropsKeys.LDAP_BASE_PROVIDER_URL, - PropsKeys.LDAP_CONTACT_CUSTOM_MAPPINGS, - PropsKeys.LDAP_CONTACT_MAPPINGS, + PropsKeys.LDAP_CONTACT_CUSTOM_MAPPINGS, PropsKeys.LDAP_CONTACT_MAPPINGS, PropsKeys.LDAP_GROUP_DEFAULT_OBJECT_CLASSES, - PropsKeys.LDAP_GROUP_MAPPINGS, - PropsKeys.LDAP_GROUPS_DN, + PropsKeys.LDAP_GROUP_MAPPINGS, PropsKeys.LDAP_GROUPS_DN, PropsKeys.LDAP_IMPORT_GROUP_SEARCH_FILTER, PropsKeys.LDAP_IMPORT_USER_SEARCH_FILTER, - PropsKeys.LDAP_SECURITY_CREDENTIALS, - PropsKeys.LDAP_SECURITY_PRINCIPAL, - PropsKeys.LDAP_SERVER_NAME, - PropsKeys.LDAP_USER_CUSTOM_MAPPINGS, + PropsKeys.LDAP_SECURITY_CREDENTIALS, PropsKeys.LDAP_SECURITY_PRINCIPAL, + PropsKeys.LDAP_SERVER_NAME, PropsKeys.LDAP_USER_CUSTOM_MAPPINGS, PropsKeys.LDAP_USER_DEFAULT_OBJECT_CLASSES, PropsKeys.LDAP_USER_MAPPINGS, PropsKeys.LDAP_USERS_DN diff --git a/portal-impl/src/com/liferay/portlet/portletconfiguration/action/EditArchivedSetupsAction.java b/portal-impl/src/com/liferay/portlet/portletconfiguration/action/EditArchivedSetupsAction.java index e9070038e7885b..ed22fe61296fab 100644 --- a/portal-impl/src/com/liferay/portlet/portletconfiguration/action/EditArchivedSetupsAction.java +++ b/portal-impl/src/com/liferay/portlet/portletconfiguration/action/EditArchivedSetupsAction.java @@ -181,8 +181,8 @@ protected void updateSetup(ActionRequest actionRequest, Portlet portlet) actionRequest, portlet.getPortletId()); PortletPreferencesServiceUtil.updateArchivePreferences( - themeDisplay.getUserId(), themeDisplay.getScopeGroupId(), - name, portlet.getRootPortletId(), setup); + themeDisplay.getUserId(), themeDisplay.getScopeGroupId(), name, + portlet.getRootPortletId(), setup); } } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCategoryLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCategoryLocalServiceImpl.java index feba28f570cbf4..ab762b1f65f1bd 100644 --- a/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCategoryLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCategoryLocalServiceImpl.java @@ -38,8 +38,8 @@ public class ShoppingCategoryLocalServiceImpl extends ShoppingCategoryLocalServiceBaseImpl { public ShoppingCategory addCategory( - long userId, long parentCategoryId, String name, - String description, ServiceContext serviceContext) + long userId, long parentCategoryId, String name, String description, + ServiceContext serviceContext) throws PortalException, SystemException { // Category diff --git a/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCouponLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCouponLocalServiceImpl.java index a41c6149adad2c..ed3ad5f7aac0fd 100644 --- a/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCouponLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCouponLocalServiceImpl.java @@ -163,8 +163,8 @@ public List search( throws SystemException { return shoppingCouponFinder.findByG_C_C_A_DT( - groupId, companyId, code, active, discountType, andOperator, - start, end); + groupId, companyId, code, active, discountType, andOperator, start, + end); } public int searchCount( diff --git a/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCouponServiceImpl.java b/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCouponServiceImpl.java index a5376081f92ca1..309d7b3a5a3a15 100644 --- a/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCouponServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingCouponServiceImpl.java @@ -44,11 +44,11 @@ public ShoppingCoupon addCoupon( ActionKeys.MANAGE_COUPONS); return shoppingCouponLocalService.addCoupon( - getUserId(), code, autoCode, name, description, - startDateMonth, startDateDay, startDateYear, startDateHour, - startDateMinute, endDateMonth, endDateDay, endDateYear, endDateHour, - endDateMinute, neverExpire, active, limitCategories, limitSkus, - minOrder, discount, discountType, serviceContext); + getUserId(), code, autoCode, name, description, startDateMonth, + startDateDay, startDateYear, startDateHour, startDateMinute, + endDateMonth, endDateDay, endDateYear, endDateHour, endDateMinute, + neverExpire, active, limitCategories, limitSkus, minOrder, discount, + discountType, serviceContext); } public void deleteCoupon(long groupId, long couponId) diff --git a/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingItemLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingItemLocalServiceImpl.java index 717fca7a46911f..3fdd3b70dd4022 100644 --- a/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingItemLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingItemLocalServiceImpl.java @@ -1,958 +1,954 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portlet.shopping.service.impl; - -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.util.FileUtil; -import com.liferay.portal.kernel.util.HttpUtil; -import com.liferay.portal.kernel.util.OrderByComparator; -import com.liferay.portal.kernel.util.PropsKeys; -import com.liferay.portal.kernel.util.StringPool; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.kernel.util.SystemProperties; -import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.model.ResourceConstants; -import com.liferay.portal.model.User; -import com.liferay.portal.service.ServiceContext; -import com.liferay.portal.util.PrefsPropsUtil; -import com.liferay.portlet.amazonrankings.model.AmazonRankings; -import com.liferay.portlet.amazonrankings.util.AmazonRankingsUtil; -import com.liferay.portlet.shopping.AmazonException; -import com.liferay.portlet.shopping.DuplicateItemSKUException; -import com.liferay.portlet.shopping.ItemLargeImageNameException; -import com.liferay.portlet.shopping.ItemLargeImageSizeException; -import com.liferay.portlet.shopping.ItemMediumImageNameException; -import com.liferay.portlet.shopping.ItemMediumImageSizeException; -import com.liferay.portlet.shopping.ItemNameException; -import com.liferay.portlet.shopping.ItemSKUException; -import com.liferay.portlet.shopping.ItemSmallImageNameException; -import com.liferay.portlet.shopping.ItemSmallImageSizeException; -import com.liferay.portlet.shopping.model.ShoppingCategory; -import com.liferay.portlet.shopping.model.ShoppingCategoryConstants; -import com.liferay.portlet.shopping.model.ShoppingItem; -import com.liferay.portlet.shopping.model.ShoppingItemField; -import com.liferay.portlet.shopping.model.ShoppingItemPrice; -import com.liferay.portlet.shopping.model.ShoppingItemPriceConstants; -import com.liferay.portlet.shopping.service.base.ShoppingItemLocalServiceBaseImpl; -import com.liferay.util.PwdGenerator; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -/** - * @author Brian Wing Shun Chan - */ -public class ShoppingItemLocalServiceImpl - extends ShoppingItemLocalServiceBaseImpl { - - public void addBookItems( - long userId, long groupId, long categoryId, String[] isbns) - throws PortalException, SystemException { - - try { - doAddBookItems(userId, groupId, categoryId, isbns); - } - catch (IOException ioe) { - throw new SystemException(ioe); - } - } - - public ShoppingItem addItem( - long userId, long groupId, long categoryId, String sku, String name, - String description, String properties, String fieldsQuantities, - boolean requiresShipping, int stockQuantity, boolean featured, - Boolean sale, boolean smallImage, String smallImageURL, - File smallImageFile, boolean mediumImage, String mediumImageURL, - File mediumImageFile, boolean largeImage, String largeImageURL, - File largeImageFile, List itemFields, - List itemPrices, ServiceContext serviceContext) - throws PortalException, SystemException { - - // Item - - User user = userPersistence.findByPrimaryKey(userId); - sku = sku.trim().toUpperCase(); - - byte[] smallImageBytes = null; - byte[] mediumImageBytes = null; - byte[] largeImageBytes = null; - - try { - smallImageBytes = FileUtil.getBytes(smallImageFile); - mediumImageBytes = FileUtil.getBytes(mediumImageFile); - largeImageBytes = FileUtil.getBytes(largeImageFile); - } - catch (IOException ioe) { - } - - Date now = new Date(); - - validate( - user.getCompanyId(), 0, sku, name, smallImage, smallImageURL, - smallImageFile, smallImageBytes, mediumImage, mediumImageURL, - mediumImageFile, mediumImageBytes, largeImage, largeImageURL, - largeImageFile, largeImageBytes); - - long itemId = counterLocalService.increment(); - - ShoppingItem item = shoppingItemPersistence.create(itemId); - - item.setGroupId(groupId); - item.setCompanyId(user.getCompanyId()); - item.setUserId(user.getUserId()); - item.setUserName(user.getFullName()); - item.setCreateDate(now); - item.setModifiedDate(now); - item.setCategoryId(categoryId); - item.setSku(sku); - item.setName(name); - item.setDescription(description); - item.setProperties(properties); - item.setFields(itemFields.size() > 0); - item.setFieldsQuantities(fieldsQuantities); - - for (ShoppingItemPrice itemPrice : itemPrices) { - if (itemPrice.getStatus() == - ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) { - - item.setMinQuantity(itemPrice.getMinQuantity()); - item.setMaxQuantity(itemPrice.getMaxQuantity()); - item.setPrice(itemPrice.getPrice()); - item.setDiscount(itemPrice.getDiscount()); - item.setTaxable(itemPrice.getTaxable()); - item.setShipping(itemPrice.getShipping()); - item.setUseShippingFormula(itemPrice.getUseShippingFormula()); - } - - if ((sale == null) && (itemPrice.getDiscount() > 0) && - ((itemPrice.getStatus() == - ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) || - (itemPrice.getStatus() == - ShoppingItemPriceConstants.STATUS_ACTIVE))) { - - sale = Boolean.TRUE; - } - } - - item.setRequiresShipping(requiresShipping); - item.setStockQuantity(stockQuantity); - item.setFeatured(featured); - item.setSale((sale != null) ? sale.booleanValue() : false); - item.setSmallImage(smallImage); - item.setSmallImageId(counterLocalService.increment()); - item.setSmallImageURL(smallImageURL); - item.setMediumImage(mediumImage); - item.setMediumImageId(counterLocalService.increment()); - item.setMediumImageURL(mediumImageURL); - item.setLargeImage(largeImage); - item.setLargeImageId(counterLocalService.increment()); - item.setLargeImageURL(largeImageURL); - - shoppingItemPersistence.update(item, false); - - // Resources - - if (serviceContext.isAddGroupPermissions() || - serviceContext.isAddGuestPermissions()) { - - addItemResources( - item, serviceContext.isAddGroupPermissions(), - serviceContext.isAddGuestPermissions()); - } - else { - addItemResources( - item, serviceContext.getGroupPermissions(), - serviceContext.getGuestPermissions()); - } - - // Images - - saveImages( - smallImage, item.getSmallImageId(), smallImageFile, smallImageBytes, - mediumImage, item.getMediumImageId(), mediumImageFile, - mediumImageBytes, largeImage, item.getLargeImageId(), - largeImageFile, largeImageBytes); - - // Item fields - - for (ShoppingItemField itemField : itemFields) { - long itemFieldId = counterLocalService.increment(); - - itemField.setItemFieldId(itemFieldId); - itemField.setItemId(itemId); - itemField.setName(checkItemField(itemField.getName())); - itemField.setValues(checkItemField(itemField.getValues())); - - shoppingItemFieldPersistence.update(itemField, false); - } - - // Item prices - - if (itemPrices.size() > 1) { - for (ShoppingItemPrice itemPrice : itemPrices) { - long itemPriceId = counterLocalService.increment(); - - itemPrice.setItemPriceId(itemPriceId); - itemPrice.setItemId(itemId); - - shoppingItemPricePersistence.update(itemPrice, false); - } - } - - return item; - } - - public void addItemResources( - long itemId, boolean addGroupPermissions, - boolean addGuestPermissions) - throws PortalException, SystemException { - - ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId); - - addItemResources(item, addGroupPermissions, addGuestPermissions); - } - - public void addItemResources( - long itemId, String[] groupPermissions, String[] guestPermissions) - throws PortalException, SystemException { - - ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId); - - addItemResources(item, groupPermissions, guestPermissions); - } - - public void addItemResources( - ShoppingItem item, boolean addGroupPermissions, - boolean addGuestPermissions) - throws PortalException, SystemException { - - resourceLocalService.addResources( - item.getCompanyId(), item.getGroupId(), item.getUserId(), - ShoppingItem.class.getName(), item.getItemId(), false, - addGroupPermissions, addGuestPermissions); - } - - public void addItemResources( - ShoppingItem item, String[] groupPermissions, - String[] guestPermissions) - throws PortalException, SystemException { - - resourceLocalService.addModelResources( - item.getCompanyId(), item.getGroupId(), item.getUserId(), - ShoppingItem.class.getName(), item.getItemId(), groupPermissions, - guestPermissions); - } - - public void deleteItem(long itemId) - throws PortalException, SystemException { - - ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId); - - deleteItem(item); - } - - public void deleteItem(ShoppingItem item) - throws PortalException, SystemException { - - // Item - - shoppingItemPersistence.remove(item); - - // Resources - - resourceLocalService.deleteResource( - item.getCompanyId(), ShoppingItem.class.getName(), - ResourceConstants.SCOPE_INDIVIDUAL, item.getItemId()); - - // Images - - imageLocalService.deleteImage(item.getSmallImageId()); - imageLocalService.deleteImage(item.getMediumImageId()); - imageLocalService.deleteImage(item.getLargeImageId()); - - // Item fields - - shoppingItemFieldPersistence.removeByItemId(item.getItemId()); - - // Item prices - - shoppingItemPricePersistence.removeByItemId(item.getItemId()); - } - - public void deleteItems(long groupId, long categoryId) - throws PortalException, SystemException { - - List items = shoppingItemPersistence.findByG_C( - groupId, categoryId); - - for (ShoppingItem item : items) { - deleteItem(item); - } - } - - public int getCategoriesItemsCount(long groupId, List categoryIds) - throws SystemException { - - return shoppingItemFinder.countByG_C(groupId, categoryIds); - } - - public List getFeaturedItems( - long groupId, long categoryId, int numOfItems) - throws SystemException { - - List featuredItems = shoppingItemFinder.findByFeatured( - groupId, new long[] {categoryId}, numOfItems); - - if (featuredItems.size() == 0) { - List childCategories = - shoppingCategoryPersistence.findByG_P(groupId, categoryId); - - if (childCategories.size() > 0) { - long[] categoryIds = new long[childCategories.size()]; - - for (int i = 0; i < childCategories.size(); i++) { - ShoppingCategory childCategory = childCategories.get(i); - - categoryIds[i] = childCategory.getCategoryId(); - } - - featuredItems = shoppingItemFinder.findByFeatured( - groupId, categoryIds, numOfItems); - } - } - - return featuredItems; - } - - public ShoppingItem getItem(long itemId) - throws PortalException, SystemException { - - return shoppingItemPersistence.findByPrimaryKey(itemId); - } - - public ShoppingItem getItem(long companyId, String sku) - throws PortalException, SystemException { - - return shoppingItemPersistence.findByC_S(companyId, sku); - } - - public ShoppingItem getItemByLargeImageId(long largeImageId) - throws PortalException, SystemException { - - return shoppingItemPersistence.findByLargeImageId(largeImageId); - } - - public ShoppingItem getItemByMediumImageId(long mediumImageId) - throws PortalException, SystemException { - - return shoppingItemPersistence.findByMediumImageId(mediumImageId); - } - - public ShoppingItem getItemBySmallImageId(long smallImageId) - throws PortalException, SystemException { - - return shoppingItemPersistence.findBySmallImageId(smallImageId); - } - - public List getItems(long groupId, long categoryId) - throws SystemException { - - return shoppingItemPersistence.findByG_C(groupId, categoryId); - } - - public List getItems( - long groupId, long categoryId, int start, int end, - OrderByComparator obc) - throws SystemException { - - return shoppingItemPersistence.findByG_C( - groupId, categoryId, start, end, obc); - } - - public int getItemsCount(long groupId, long categoryId) - throws SystemException { - - return shoppingItemPersistence.countByG_C(groupId, categoryId); - } - - public ShoppingItem[] getItemsPrevAndNext( - long itemId, OrderByComparator obc) - throws PortalException, SystemException { - - ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId); - - return shoppingItemPersistence.findByG_C_PrevAndNext( - item.getItemId(), item.getGroupId(), item.getCategoryId(), obc); - } - - public List getSaleItems( - long groupId, long categoryId, int numOfItems) - throws SystemException { - - List saleItems = shoppingItemFinder.findBySale( - groupId, new long[] {categoryId}, numOfItems); - - if (saleItems.size() == 0) { - List childCategories = - shoppingCategoryPersistence.findByG_P(groupId, categoryId); - - if (childCategories.size() > 0) { - long[] categoryIds = new long[childCategories.size()]; - - for (int i = 0; i < childCategories.size(); i++) { - ShoppingCategory childCategory = childCategories.get(i); - - categoryIds[i] = childCategory.getCategoryId(); - } - - saleItems = shoppingItemFinder.findBySale( - groupId, categoryIds, numOfItems); - } - } - - return saleItems; - } - - public List search( - long groupId, long[] categoryIds, String keywords, int start, - int end) - throws SystemException { - - return shoppingItemFinder.findByKeywords( - groupId, categoryIds, keywords, start, end); - } - - public int searchCount(long groupId, long[] categoryIds, String keywords) - throws SystemException { - - return shoppingItemFinder.countByKeywords( - groupId, categoryIds, keywords); - } - - public ShoppingItem updateItem( - long userId, long itemId, long groupId, long categoryId, String sku, - String name, String description, String properties, - String fieldsQuantities, boolean requiresShipping, - int stockQuantity, boolean featured, Boolean sale, - boolean smallImage, String smallImageURL, File smallImageFile, - boolean mediumImage, String mediumImageURL, File mediumImageFile, - boolean largeImage, String largeImageURL, File largeImageFile, - List itemFields, - List itemPrices, ServiceContext serviceContext) - throws PortalException, SystemException { - - // Item - - ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId); - - User user = userPersistence.findByPrimaryKey(userId); - categoryId = getCategory(item, categoryId); - sku = sku.trim().toUpperCase(); - - byte[] smallImageBytes = null; - byte[] mediumImageBytes = null; - byte[] largeImageBytes = null; - - try { - smallImageBytes = FileUtil.getBytes(smallImageFile); - mediumImageBytes = FileUtil.getBytes(mediumImageFile); - largeImageBytes = FileUtil.getBytes(largeImageFile); - } - catch (IOException ioe) { - } - - validate( - user.getCompanyId(), itemId, sku, name, smallImage, smallImageURL, - smallImageFile, smallImageBytes, mediumImage, mediumImageURL, - mediumImageFile, mediumImageBytes, largeImage, largeImageURL, - largeImageFile, largeImageBytes); - - item.setModifiedDate(new Date()); - item.setCategoryId(categoryId); - item.setSku(sku); - item.setName(name); - item.setDescription(description); - item.setProperties(properties); - item.setFields(itemFields.size() > 0); - item.setFieldsQuantities(fieldsQuantities); - - for (ShoppingItemPrice itemPrice : itemPrices) { - if (itemPrice.getStatus() == - ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) { - - item.setMinQuantity(itemPrice.getMinQuantity()); - item.setMaxQuantity(itemPrice.getMaxQuantity()); - item.setPrice(itemPrice.getPrice()); - item.setDiscount(itemPrice.getDiscount()); - item.setTaxable(itemPrice.getTaxable()); - item.setShipping(itemPrice.getShipping()); - item.setUseShippingFormula(itemPrice.getUseShippingFormula()); - } - - if ((sale == null) && (itemPrice.getDiscount() > 0) && - ((itemPrice.getStatus() == - ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) || - (itemPrice.getStatus() == - ShoppingItemPriceConstants.STATUS_ACTIVE))) { - - sale = Boolean.TRUE; - } - } - - item.setRequiresShipping(requiresShipping); - item.setStockQuantity(stockQuantity); - item.setFeatured(featured); - item.setSale((sale != null) ? sale.booleanValue() : false); - item.setSmallImage(smallImage); - item.setSmallImageURL(smallImageURL); - item.setMediumImage(mediumImage); - item.setMediumImageURL(mediumImageURL); - item.setLargeImage(largeImage); - item.setLargeImageURL(largeImageURL); - - shoppingItemPersistence.update(item, false); - - // Images - - saveImages( - smallImage, item.getSmallImageId(), smallImageFile, smallImageBytes, - mediumImage, item.getMediumImageId(), mediumImageFile, - mediumImageBytes, largeImage, item.getLargeImageId(), - largeImageFile, largeImageBytes); - - // Item fields - - shoppingItemFieldPersistence.removeByItemId(itemId); - - for (ShoppingItemField itemField : itemFields) { - long itemFieldId = counterLocalService.increment(); - - itemField.setItemFieldId(itemFieldId); - itemField.setItemId(itemId); - itemField.setName(checkItemField(itemField.getName())); - itemField.setValues(checkItemField(itemField.getValues())); - - shoppingItemFieldPersistence.update(itemField, false); - } - - // Item prices - - shoppingItemPricePersistence.removeByItemId(itemId); - - if (itemPrices.size() > 1) { - for (ShoppingItemPrice itemPrice : itemPrices) { - long itemPriceId = counterLocalService.increment(); - - itemPrice.setItemPriceId(itemPriceId); - itemPrice.setItemId(itemId); - - shoppingItemPricePersistence.update(itemPrice, false); - } - } - - return item; - } - - protected String checkItemField(String value) { - return StringUtil.replace( - value, - new String[] { - "\"", "&", "'", ".", "=", "|" - }, - new String[] { - StringPool.BLANK, - StringPool.BLANK, - StringPool.BLANK, - StringPool.BLANK, - StringPool.BLANK, - StringPool.BLANK - } - ); - } - - protected void doAddBookItems( - long userId, long groupId, long categoryId, String[] isbns) - throws IOException, PortalException, SystemException { - - if (!AmazonRankingsUtil.isEnabled()) { - throw new AmazonException("Amazon integration is not enabled"); - } - - String tmpDir = SystemProperties.get(SystemProperties.TMP_DIR); - - for (int i = 0; (i < isbns.length) && (i < 50); i++) { - String isbn = isbns[i]; - - AmazonRankings amazonRankings = - AmazonRankingsUtil.getAmazonRankings(isbn); - - if (amazonRankings == null) { - continue; - } - - String name = amazonRankings.getProductName(); - String description = StringPool.BLANK; - String properties = getBookProperties(amazonRankings); - - int minQuantity = 0; - int maxQuantity = 0; - double price = amazonRankings.getListPrice(); - double discount = 1 - amazonRankings.getOurPrice() / price; - boolean taxable = true; - double shipping = 0.0; - boolean useShippingFormula = true; - - ShoppingItemPrice itemPrice = shoppingItemPricePersistence.create( - 0); - - itemPrice.setMinQuantity(minQuantity); - itemPrice.setMaxQuantity(maxQuantity); - itemPrice.setPrice(price); - itemPrice.setDiscount(discount); - itemPrice.setTaxable(taxable); - itemPrice.setShipping(shipping); - itemPrice.setUseShippingFormula(useShippingFormula); - itemPrice.setStatus( - ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT); - - boolean requiresShipping = true; - int stockQuantity = 0; - boolean featured = false; - Boolean sale = null; - - // Small image - - boolean smallImage = true; - String smallImageURL = StringPool.BLANK; - File smallImageFile = new File( - tmpDir + File.separatorChar + - PwdGenerator.getPassword( - PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg"); - - byte[] smallImageBytes = HttpUtil.URLtoByteArray( - amazonRankings.getSmallImageURL()); - - if (smallImageBytes.length < 1024) { - smallImage = false; - } - else { - OutputStream os = new FileOutputStream(smallImageFile); - - os.write(smallImageBytes); - - os.close(); - } - - // Medium image - - boolean mediumImage = true; - String mediumImageURL = StringPool.BLANK; - File mediumImageFile = new File( - tmpDir + File.separatorChar + - PwdGenerator.getPassword( - PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg"); - - byte[] mediumImageBytes = HttpUtil.URLtoByteArray( - amazonRankings.getMediumImageURL()); - - if (mediumImageBytes.length < 1024) { - mediumImage = false; - } - else { - OutputStream os = new FileOutputStream(mediumImageFile); - - os.write(mediumImageBytes); - - os.close(); - } - - // Large image - - boolean largeImage = true; - String largeImageURL = StringPool.BLANK; - File largeImageFile = new File( - tmpDir + File.separatorChar + - PwdGenerator.getPassword( - PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg"); - - byte[] largeImageBytes = HttpUtil.URLtoByteArray( - amazonRankings.getLargeImageURL()); - - if (largeImageBytes.length < 1024) { - largeImage = false; - } - else { - OutputStream os = new FileOutputStream(largeImageFile); - - os.write(largeImageBytes); - - os.close(); - } - - List itemFields = - new ArrayList(); - - List itemPrices = - new ArrayList(); - - itemPrices.add(itemPrice); - - ServiceContext serviceContext = new ServiceContext(); - - serviceContext.setAddGroupPermissions(true); - serviceContext.setAddGuestPermissions(true); - - addItem( - userId, groupId, categoryId, isbn, name, description, - properties, StringPool.BLANK, requiresShipping, stockQuantity, - featured, sale, smallImage, smallImageURL, smallImageFile, - mediumImage, mediumImageURL, mediumImageFile, largeImage, - largeImageURL, largeImageFile, itemFields, itemPrices, - serviceContext); - - smallImageFile.delete(); - mediumImageFile.delete(); - largeImageFile.delete(); - } - } - - protected String getBookProperties(AmazonRankings amazonRankings) { - String isbn = amazonRankings.getISBN(); - - String authors = StringUtil.merge(amazonRankings.getAuthors(), ", "); - - String publisher = - amazonRankings.getManufacturer() + "; (" + - amazonRankings.getReleaseDateAsString() + ")"; - - String properties = - "ISBN=" + isbn + "\nAuthor=" + authors + "\nPublisher=" + publisher; - - return properties; - } - - protected long getCategory(ShoppingItem item, long categoryId) - throws SystemException { - - if ((item.getCategoryId() != categoryId) && - (categoryId != - ShoppingCategoryConstants.DEFAULT_PARENT_CATEGORY_ID)) { - - ShoppingCategory newCategory = - shoppingCategoryPersistence.fetchByPrimaryKey(categoryId); - - if ((newCategory == null) || - (item.getGroupId() != newCategory.getGroupId())) { - - categoryId = item.getCategoryId(); - } - } - - return categoryId; - } - - protected void saveImages( - boolean smallImage, long smallImageId, File smallImageFile, - byte[] smallImageBytes, boolean mediumImage, long mediumImageId, - File mediumImageFile, byte[] mediumImageBytes, boolean largeImage, - long largeImageId, File largeImageFile, byte[] largeImageBytes) - throws PortalException, SystemException { - - // Small image - - if (smallImage) { - if ((smallImageFile != null) && (smallImageBytes != null)) { - imageLocalService.updateImage(smallImageId, smallImageBytes); - } - } - else { - imageLocalService.deleteImage(smallImageId); - } - - // Medium image - - if (mediumImage) { - if ((mediumImageFile != null) && (mediumImageBytes != null)) { - imageLocalService.updateImage(mediumImageId, mediumImageBytes); - } - } - else { - imageLocalService.deleteImage(mediumImageId); - } - - // Large image - - if (largeImage) { - if ((largeImageFile != null) && (largeImageBytes != null)) { - imageLocalService.updateImage(largeImageId, largeImageBytes); - } - } - else { - imageLocalService.deleteImage(largeImageId); - } - } - - protected void validate( - long companyId, long itemId, String sku, String name, - boolean smallImage, String smallImageURL, File smallImageFile, - byte[] smallImageBytes, boolean mediumImage, String mediumImageURL, - File mediumImageFile, byte[] mediumImageBytes, boolean largeImage, - String largeImageURL, File largeImageFile, byte[] largeImageBytes) - throws PortalException, SystemException { - - if (Validator.isNull(sku)) { - throw new ItemSKUException(); - } - - ShoppingItem item = shoppingItemPersistence.fetchByC_S(companyId, sku); - - if (item != null) { - if (itemId > 0) { - if (item.getItemId() != itemId) { - throw new DuplicateItemSKUException(); - } - } - else { - throw new DuplicateItemSKUException(); - } - } - - if (Validator.isNull(name)) { - throw new ItemNameException(); - } - - String[] imageExtensions = PrefsPropsUtil.getStringArray( - PropsKeys.SHOPPING_IMAGE_EXTENSIONS, StringPool.COMMA); - - // Small image - - if (smallImage && Validator.isNull(smallImageURL) && - smallImageFile != null && smallImageBytes != null) { - - String smallImageName = smallImageFile.getName(); - - if (smallImageName != null) { - boolean validSmallImageExtension = false; - - for (int i = 0; i < imageExtensions.length; i++) { - if (StringPool.STAR.equals(imageExtensions[i]) || - StringUtil.endsWith( - smallImageName, imageExtensions[i])) { - - validSmallImageExtension = true; - - break; - } - } - - if (!validSmallImageExtension) { - throw new ItemSmallImageNameException(smallImageName); - } - } - - long smallImageMaxSize = PrefsPropsUtil.getLong( - PropsKeys.SHOPPING_IMAGE_MEDIUM_MAX_SIZE); - - if ((smallImageMaxSize > 0) && - ((smallImageBytes == null) || - (smallImageBytes.length > smallImageMaxSize))) { - - throw new ItemSmallImageSizeException(); - } - } - - // Medium image - - if (mediumImage && Validator.isNull(mediumImageURL) && - mediumImageFile != null && mediumImageBytes != null) { - - String mediumImageName = mediumImageFile.getName(); - - if (mediumImageName != null) { - boolean validMediumImageExtension = false; - - for (int i = 0; i < imageExtensions.length; i++) { - if (StringPool.STAR.equals(imageExtensions[i]) || - StringUtil.endsWith( - mediumImageName, imageExtensions[i])) { - - validMediumImageExtension = true; - - break; - } - } - - if (!validMediumImageExtension) { - throw new ItemMediumImageNameException(mediumImageName); - } - } - - long mediumImageMaxSize = PrefsPropsUtil.getLong( - PropsKeys.SHOPPING_IMAGE_MEDIUM_MAX_SIZE); - - if ((mediumImageMaxSize > 0) && - ((mediumImageBytes == null) || - (mediumImageBytes.length > mediumImageMaxSize))) { - - throw new ItemMediumImageSizeException(); - } - } - - // Large image - - if (largeImage && Validator.isNull(largeImageURL) && - largeImageFile != null && largeImageBytes != null) { - - String largeImageName = largeImageFile.getName(); - - if (largeImageName != null) { - boolean validLargeImageExtension = false; - - for (int i = 0; i < imageExtensions.length; i++) { - if (StringPool.STAR.equals(imageExtensions[i]) || - StringUtil.endsWith( - largeImageName, imageExtensions[i])) { - - validLargeImageExtension = true; - - break; - } - } - - if (!validLargeImageExtension) { - throw new ItemLargeImageNameException(largeImageName); - } - } - - long largeImageMaxSize = PrefsPropsUtil.getLong( - PropsKeys.SHOPPING_IMAGE_LARGE_MAX_SIZE); - - if ((largeImageMaxSize > 0) && - ((largeImageBytes == null) || - (largeImageBytes.length > largeImageMaxSize))) { - - throw new ItemLargeImageSizeException(); - } - } - } - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portlet.shopping.service.impl; + +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.util.FileUtil; +import com.liferay.portal.kernel.util.HttpUtil; +import com.liferay.portal.kernel.util.OrderByComparator; +import com.liferay.portal.kernel.util.PropsKeys; +import com.liferay.portal.kernel.util.StringPool; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.SystemProperties; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.model.ResourceConstants; +import com.liferay.portal.model.User; +import com.liferay.portal.service.ServiceContext; +import com.liferay.portal.util.PrefsPropsUtil; +import com.liferay.portlet.amazonrankings.model.AmazonRankings; +import com.liferay.portlet.amazonrankings.util.AmazonRankingsUtil; +import com.liferay.portlet.shopping.AmazonException; +import com.liferay.portlet.shopping.DuplicateItemSKUException; +import com.liferay.portlet.shopping.ItemLargeImageNameException; +import com.liferay.portlet.shopping.ItemLargeImageSizeException; +import com.liferay.portlet.shopping.ItemMediumImageNameException; +import com.liferay.portlet.shopping.ItemMediumImageSizeException; +import com.liferay.portlet.shopping.ItemNameException; +import com.liferay.portlet.shopping.ItemSKUException; +import com.liferay.portlet.shopping.ItemSmallImageNameException; +import com.liferay.portlet.shopping.ItemSmallImageSizeException; +import com.liferay.portlet.shopping.model.ShoppingCategory; +import com.liferay.portlet.shopping.model.ShoppingCategoryConstants; +import com.liferay.portlet.shopping.model.ShoppingItem; +import com.liferay.portlet.shopping.model.ShoppingItemField; +import com.liferay.portlet.shopping.model.ShoppingItemPrice; +import com.liferay.portlet.shopping.model.ShoppingItemPriceConstants; +import com.liferay.portlet.shopping.service.base.ShoppingItemLocalServiceBaseImpl; +import com.liferay.util.PwdGenerator; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * @author Brian Wing Shun Chan + */ +public class ShoppingItemLocalServiceImpl + extends ShoppingItemLocalServiceBaseImpl { + + public void addBookItems( + long userId, long groupId, long categoryId, String[] isbns) + throws PortalException, SystemException { + + try { + doAddBookItems(userId, groupId, categoryId, isbns); + } + catch (IOException ioe) { + throw new SystemException(ioe); + } + } + + public ShoppingItem addItem( + long userId, long groupId, long categoryId, String sku, String name, + String description, String properties, String fieldsQuantities, + boolean requiresShipping, int stockQuantity, boolean featured, + Boolean sale, boolean smallImage, String smallImageURL, + File smallImageFile, boolean mediumImage, String mediumImageURL, + File mediumImageFile, boolean largeImage, String largeImageURL, + File largeImageFile, List itemFields, + List itemPrices, ServiceContext serviceContext) + throws PortalException, SystemException { + + // Item + + User user = userPersistence.findByPrimaryKey(userId); + sku = sku.trim().toUpperCase(); + + byte[] smallImageBytes = null; + byte[] mediumImageBytes = null; + byte[] largeImageBytes = null; + + try { + smallImageBytes = FileUtil.getBytes(smallImageFile); + mediumImageBytes = FileUtil.getBytes(mediumImageFile); + largeImageBytes = FileUtil.getBytes(largeImageFile); + } + catch (IOException ioe) { + } + + Date now = new Date(); + + validate( + user.getCompanyId(), 0, sku, name, smallImage, smallImageURL, + smallImageFile, smallImageBytes, mediumImage, mediumImageURL, + mediumImageFile, mediumImageBytes, largeImage, largeImageURL, + largeImageFile, largeImageBytes); + + long itemId = counterLocalService.increment(); + + ShoppingItem item = shoppingItemPersistence.create(itemId); + + item.setGroupId(groupId); + item.setCompanyId(user.getCompanyId()); + item.setUserId(user.getUserId()); + item.setUserName(user.getFullName()); + item.setCreateDate(now); + item.setModifiedDate(now); + item.setCategoryId(categoryId); + item.setSku(sku); + item.setName(name); + item.setDescription(description); + item.setProperties(properties); + item.setFields(itemFields.size() > 0); + item.setFieldsQuantities(fieldsQuantities); + + for (ShoppingItemPrice itemPrice : itemPrices) { + if (itemPrice.getStatus() == + ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) { + + item.setMinQuantity(itemPrice.getMinQuantity()); + item.setMaxQuantity(itemPrice.getMaxQuantity()); + item.setPrice(itemPrice.getPrice()); + item.setDiscount(itemPrice.getDiscount()); + item.setTaxable(itemPrice.getTaxable()); + item.setShipping(itemPrice.getShipping()); + item.setUseShippingFormula(itemPrice.getUseShippingFormula()); + } + + if ((sale == null) && (itemPrice.getDiscount() > 0) && + ((itemPrice.getStatus() == + ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) || + (itemPrice.getStatus() == + ShoppingItemPriceConstants.STATUS_ACTIVE))) { + + sale = Boolean.TRUE; + } + } + + item.setRequiresShipping(requiresShipping); + item.setStockQuantity(stockQuantity); + item.setFeatured(featured); + item.setSale((sale != null) ? sale.booleanValue() : false); + item.setSmallImage(smallImage); + item.setSmallImageId(counterLocalService.increment()); + item.setSmallImageURL(smallImageURL); + item.setMediumImage(mediumImage); + item.setMediumImageId(counterLocalService.increment()); + item.setMediumImageURL(mediumImageURL); + item.setLargeImage(largeImage); + item.setLargeImageId(counterLocalService.increment()); + item.setLargeImageURL(largeImageURL); + + shoppingItemPersistence.update(item, false); + + // Resources + + if (serviceContext.isAddGroupPermissions() || + serviceContext.isAddGuestPermissions()) { + + addItemResources( + item, serviceContext.isAddGroupPermissions(), + serviceContext.isAddGuestPermissions()); + } + else { + addItemResources( + item, serviceContext.getGroupPermissions(), + serviceContext.getGuestPermissions()); + } + + // Images + + saveImages( + smallImage, item.getSmallImageId(), smallImageFile, smallImageBytes, + mediumImage, item.getMediumImageId(), mediumImageFile, + mediumImageBytes, largeImage, item.getLargeImageId(), + largeImageFile, largeImageBytes); + + // Item fields + + for (ShoppingItemField itemField : itemFields) { + long itemFieldId = counterLocalService.increment(); + + itemField.setItemFieldId(itemFieldId); + itemField.setItemId(itemId); + itemField.setName(checkItemField(itemField.getName())); + itemField.setValues(checkItemField(itemField.getValues())); + + shoppingItemFieldPersistence.update(itemField, false); + } + + // Item prices + + if (itemPrices.size() > 1) { + for (ShoppingItemPrice itemPrice : itemPrices) { + long itemPriceId = counterLocalService.increment(); + + itemPrice.setItemPriceId(itemPriceId); + itemPrice.setItemId(itemId); + + shoppingItemPricePersistence.update(itemPrice, false); + } + } + + return item; + } + + public void addItemResources( + long itemId, boolean addGroupPermissions, + boolean addGuestPermissions) + throws PortalException, SystemException { + + ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId); + + addItemResources(item, addGroupPermissions, addGuestPermissions); + } + + public void addItemResources( + long itemId, String[] groupPermissions, String[] guestPermissions) + throws PortalException, SystemException { + + ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId); + + addItemResources(item, groupPermissions, guestPermissions); + } + + public void addItemResources( + ShoppingItem item, boolean addGroupPermissions, + boolean addGuestPermissions) + throws PortalException, SystemException { + + resourceLocalService.addResources( + item.getCompanyId(), item.getGroupId(), item.getUserId(), + ShoppingItem.class.getName(), item.getItemId(), false, + addGroupPermissions, addGuestPermissions); + } + + public void addItemResources( + ShoppingItem item, String[] groupPermissions, + String[] guestPermissions) + throws PortalException, SystemException { + + resourceLocalService.addModelResources( + item.getCompanyId(), item.getGroupId(), item.getUserId(), + ShoppingItem.class.getName(), item.getItemId(), groupPermissions, + guestPermissions); + } + + public void deleteItem(long itemId) + throws PortalException, SystemException { + + ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId); + + deleteItem(item); + } + + public void deleteItem(ShoppingItem item) + throws PortalException, SystemException { + + // Item + + shoppingItemPersistence.remove(item); + + // Resources + + resourceLocalService.deleteResource( + item.getCompanyId(), ShoppingItem.class.getName(), + ResourceConstants.SCOPE_INDIVIDUAL, item.getItemId()); + + // Images + + imageLocalService.deleteImage(item.getSmallImageId()); + imageLocalService.deleteImage(item.getMediumImageId()); + imageLocalService.deleteImage(item.getLargeImageId()); + + // Item fields + + shoppingItemFieldPersistence.removeByItemId(item.getItemId()); + + // Item prices + + shoppingItemPricePersistence.removeByItemId(item.getItemId()); + } + + public void deleteItems(long groupId, long categoryId) + throws PortalException, SystemException { + + List items = shoppingItemPersistence.findByG_C( + groupId, categoryId); + + for (ShoppingItem item : items) { + deleteItem(item); + } + } + + public int getCategoriesItemsCount(long groupId, List categoryIds) + throws SystemException { + + return shoppingItemFinder.countByG_C(groupId, categoryIds); + } + + public List getFeaturedItems( + long groupId, long categoryId, int numOfItems) + throws SystemException { + + List featuredItems = shoppingItemFinder.findByFeatured( + groupId, new long[] {categoryId}, numOfItems); + + if (featuredItems.size() == 0) { + List childCategories = + shoppingCategoryPersistence.findByG_P(groupId, categoryId); + + if (childCategories.size() > 0) { + long[] categoryIds = new long[childCategories.size()]; + + for (int i = 0; i < childCategories.size(); i++) { + ShoppingCategory childCategory = childCategories.get(i); + + categoryIds[i] = childCategory.getCategoryId(); + } + + featuredItems = shoppingItemFinder.findByFeatured( + groupId, categoryIds, numOfItems); + } + } + + return featuredItems; + } + + public ShoppingItem getItem(long itemId) + throws PortalException, SystemException { + + return shoppingItemPersistence.findByPrimaryKey(itemId); + } + + public ShoppingItem getItem(long companyId, String sku) + throws PortalException, SystemException { + + return shoppingItemPersistence.findByC_S(companyId, sku); + } + + public ShoppingItem getItemByLargeImageId(long largeImageId) + throws PortalException, SystemException { + + return shoppingItemPersistence.findByLargeImageId(largeImageId); + } + + public ShoppingItem getItemByMediumImageId(long mediumImageId) + throws PortalException, SystemException { + + return shoppingItemPersistence.findByMediumImageId(mediumImageId); + } + + public ShoppingItem getItemBySmallImageId(long smallImageId) + throws PortalException, SystemException { + + return shoppingItemPersistence.findBySmallImageId(smallImageId); + } + + public List getItems(long groupId, long categoryId) + throws SystemException { + + return shoppingItemPersistence.findByG_C(groupId, categoryId); + } + + public List getItems( + long groupId, long categoryId, int start, int end, + OrderByComparator obc) + throws SystemException { + + return shoppingItemPersistence.findByG_C( + groupId, categoryId, start, end, obc); + } + + public int getItemsCount(long groupId, long categoryId) + throws SystemException { + + return shoppingItemPersistence.countByG_C(groupId, categoryId); + } + + public ShoppingItem[] getItemsPrevAndNext( + long itemId, OrderByComparator obc) + throws PortalException, SystemException { + + ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId); + + return shoppingItemPersistence.findByG_C_PrevAndNext( + item.getItemId(), item.getGroupId(), item.getCategoryId(), obc); + } + + public List getSaleItems( + long groupId, long categoryId, int numOfItems) + throws SystemException { + + List saleItems = shoppingItemFinder.findBySale( + groupId, new long[] {categoryId}, numOfItems); + + if (saleItems.size() == 0) { + List childCategories = + shoppingCategoryPersistence.findByG_P(groupId, categoryId); + + if (childCategories.size() > 0) { + long[] categoryIds = new long[childCategories.size()]; + + for (int i = 0; i < childCategories.size(); i++) { + ShoppingCategory childCategory = childCategories.get(i); + + categoryIds[i] = childCategory.getCategoryId(); + } + + saleItems = shoppingItemFinder.findBySale( + groupId, categoryIds, numOfItems); + } + } + + return saleItems; + } + + public List search( + long groupId, long[] categoryIds, String keywords, int start, + int end) + throws SystemException { + + return shoppingItemFinder.findByKeywords( + groupId, categoryIds, keywords, start, end); + } + + public int searchCount(long groupId, long[] categoryIds, String keywords) + throws SystemException { + + return shoppingItemFinder.countByKeywords( + groupId, categoryIds, keywords); + } + + public ShoppingItem updateItem( + long userId, long itemId, long groupId, long categoryId, String sku, + String name, String description, String properties, + String fieldsQuantities, boolean requiresShipping, + int stockQuantity, boolean featured, Boolean sale, + boolean smallImage, String smallImageURL, File smallImageFile, + boolean mediumImage, String mediumImageURL, File mediumImageFile, + boolean largeImage, String largeImageURL, File largeImageFile, + List itemFields, + List itemPrices, ServiceContext serviceContext) + throws PortalException, SystemException { + + // Item + + ShoppingItem item = shoppingItemPersistence.findByPrimaryKey(itemId); + + User user = userPersistence.findByPrimaryKey(userId); + categoryId = getCategory(item, categoryId); + sku = sku.trim().toUpperCase(); + + byte[] smallImageBytes = null; + byte[] mediumImageBytes = null; + byte[] largeImageBytes = null; + + try { + smallImageBytes = FileUtil.getBytes(smallImageFile); + mediumImageBytes = FileUtil.getBytes(mediumImageFile); + largeImageBytes = FileUtil.getBytes(largeImageFile); + } + catch (IOException ioe) { + } + + validate( + user.getCompanyId(), itemId, sku, name, smallImage, smallImageURL, + smallImageFile, smallImageBytes, mediumImage, mediumImageURL, + mediumImageFile, mediumImageBytes, largeImage, largeImageURL, + largeImageFile, largeImageBytes); + + item.setModifiedDate(new Date()); + item.setCategoryId(categoryId); + item.setSku(sku); + item.setName(name); + item.setDescription(description); + item.setProperties(properties); + item.setFields(itemFields.size() > 0); + item.setFieldsQuantities(fieldsQuantities); + + for (ShoppingItemPrice itemPrice : itemPrices) { + if (itemPrice.getStatus() == + ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) { + + item.setMinQuantity(itemPrice.getMinQuantity()); + item.setMaxQuantity(itemPrice.getMaxQuantity()); + item.setPrice(itemPrice.getPrice()); + item.setDiscount(itemPrice.getDiscount()); + item.setTaxable(itemPrice.getTaxable()); + item.setShipping(itemPrice.getShipping()); + item.setUseShippingFormula(itemPrice.getUseShippingFormula()); + } + + if ((sale == null) && (itemPrice.getDiscount() > 0) && + ((itemPrice.getStatus() == + ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT) || + (itemPrice.getStatus() == + ShoppingItemPriceConstants.STATUS_ACTIVE))) { + + sale = Boolean.TRUE; + } + } + + item.setRequiresShipping(requiresShipping); + item.setStockQuantity(stockQuantity); + item.setFeatured(featured); + item.setSale((sale != null) ? sale.booleanValue() : false); + item.setSmallImage(smallImage); + item.setSmallImageURL(smallImageURL); + item.setMediumImage(mediumImage); + item.setMediumImageURL(mediumImageURL); + item.setLargeImage(largeImage); + item.setLargeImageURL(largeImageURL); + + shoppingItemPersistence.update(item, false); + + // Images + + saveImages( + smallImage, item.getSmallImageId(), smallImageFile, smallImageBytes, + mediumImage, item.getMediumImageId(), mediumImageFile, + mediumImageBytes, largeImage, item.getLargeImageId(), + largeImageFile, largeImageBytes); + + // Item fields + + shoppingItemFieldPersistence.removeByItemId(itemId); + + for (ShoppingItemField itemField : itemFields) { + long itemFieldId = counterLocalService.increment(); + + itemField.setItemFieldId(itemFieldId); + itemField.setItemId(itemId); + itemField.setName(checkItemField(itemField.getName())); + itemField.setValues(checkItemField(itemField.getValues())); + + shoppingItemFieldPersistence.update(itemField, false); + } + + // Item prices + + shoppingItemPricePersistence.removeByItemId(itemId); + + if (itemPrices.size() > 1) { + for (ShoppingItemPrice itemPrice : itemPrices) { + long itemPriceId = counterLocalService.increment(); + + itemPrice.setItemPriceId(itemPriceId); + itemPrice.setItemId(itemId); + + shoppingItemPricePersistence.update(itemPrice, false); + } + } + + return item; + } + + protected String checkItemField(String value) { + return StringUtil.replace( + value, + new String[] { + "\"", "&", "'", ".", "=", "|" + }, + new String[] { + StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, + StringPool.BLANK, StringPool.BLANK, StringPool.BLANK + } + ); + } + + protected void doAddBookItems( + long userId, long groupId, long categoryId, String[] isbns) + throws IOException, PortalException, SystemException { + + if (!AmazonRankingsUtil.isEnabled()) { + throw new AmazonException("Amazon integration is not enabled"); + } + + String tmpDir = SystemProperties.get(SystemProperties.TMP_DIR); + + for (int i = 0; (i < isbns.length) && (i < 50); i++) { + String isbn = isbns[i]; + + AmazonRankings amazonRankings = + AmazonRankingsUtil.getAmazonRankings(isbn); + + if (amazonRankings == null) { + continue; + } + + String name = amazonRankings.getProductName(); + String description = StringPool.BLANK; + String properties = getBookProperties(amazonRankings); + + int minQuantity = 0; + int maxQuantity = 0; + double price = amazonRankings.getListPrice(); + double discount = 1 - amazonRankings.getOurPrice() / price; + boolean taxable = true; + double shipping = 0.0; + boolean useShippingFormula = true; + + ShoppingItemPrice itemPrice = shoppingItemPricePersistence.create( + 0); + + itemPrice.setMinQuantity(minQuantity); + itemPrice.setMaxQuantity(maxQuantity); + itemPrice.setPrice(price); + itemPrice.setDiscount(discount); + itemPrice.setTaxable(taxable); + itemPrice.setShipping(shipping); + itemPrice.setUseShippingFormula(useShippingFormula); + itemPrice.setStatus( + ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT); + + boolean requiresShipping = true; + int stockQuantity = 0; + boolean featured = false; + Boolean sale = null; + + // Small image + + boolean smallImage = true; + String smallImageURL = StringPool.BLANK; + File smallImageFile = new File( + tmpDir + File.separatorChar + + PwdGenerator.getPassword( + PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg"); + + byte[] smallImageBytes = HttpUtil.URLtoByteArray( + amazonRankings.getSmallImageURL()); + + if (smallImageBytes.length < 1024) { + smallImage = false; + } + else { + OutputStream os = new FileOutputStream(smallImageFile); + + os.write(smallImageBytes); + + os.close(); + } + + // Medium image + + boolean mediumImage = true; + String mediumImageURL = StringPool.BLANK; + File mediumImageFile = new File( + tmpDir + File.separatorChar + + PwdGenerator.getPassword( + PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg"); + + byte[] mediumImageBytes = HttpUtil.URLtoByteArray( + amazonRankings.getMediumImageURL()); + + if (mediumImageBytes.length < 1024) { + mediumImage = false; + } + else { + OutputStream os = new FileOutputStream(mediumImageFile); + + os.write(mediumImageBytes); + + os.close(); + } + + // Large image + + boolean largeImage = true; + String largeImageURL = StringPool.BLANK; + File largeImageFile = new File( + tmpDir + File.separatorChar + + PwdGenerator.getPassword( + PwdGenerator.KEY1 + PwdGenerator.KEY2, 12) + ".jpg"); + + byte[] largeImageBytes = HttpUtil.URLtoByteArray( + amazonRankings.getLargeImageURL()); + + if (largeImageBytes.length < 1024) { + largeImage = false; + } + else { + OutputStream os = new FileOutputStream(largeImageFile); + + os.write(largeImageBytes); + + os.close(); + } + + List itemFields = + new ArrayList(); + + List itemPrices = + new ArrayList(); + + itemPrices.add(itemPrice); + + ServiceContext serviceContext = new ServiceContext(); + + serviceContext.setAddGroupPermissions(true); + serviceContext.setAddGuestPermissions(true); + + addItem( + userId, groupId, categoryId, isbn, name, description, + properties, StringPool.BLANK, requiresShipping, stockQuantity, + featured, sale, smallImage, smallImageURL, smallImageFile, + mediumImage, mediumImageURL, mediumImageFile, largeImage, + largeImageURL, largeImageFile, itemFields, itemPrices, + serviceContext); + + smallImageFile.delete(); + mediumImageFile.delete(); + largeImageFile.delete(); + } + } + + protected String getBookProperties(AmazonRankings amazonRankings) { + String isbn = amazonRankings.getISBN(); + + String authors = StringUtil.merge(amazonRankings.getAuthors(), ", "); + + String publisher = + amazonRankings.getManufacturer() + "; (" + + amazonRankings.getReleaseDateAsString() + ")"; + + String properties = + "ISBN=" + isbn + "\nAuthor=" + authors + "\nPublisher=" + publisher; + + return properties; + } + + protected long getCategory(ShoppingItem item, long categoryId) + throws SystemException { + + if ((item.getCategoryId() != categoryId) && + (categoryId != + ShoppingCategoryConstants.DEFAULT_PARENT_CATEGORY_ID)) { + + ShoppingCategory newCategory = + shoppingCategoryPersistence.fetchByPrimaryKey(categoryId); + + if ((newCategory == null) || + (item.getGroupId() != newCategory.getGroupId())) { + + categoryId = item.getCategoryId(); + } + } + + return categoryId; + } + + protected void saveImages( + boolean smallImage, long smallImageId, File smallImageFile, + byte[] smallImageBytes, boolean mediumImage, long mediumImageId, + File mediumImageFile, byte[] mediumImageBytes, boolean largeImage, + long largeImageId, File largeImageFile, byte[] largeImageBytes) + throws PortalException, SystemException { + + // Small image + + if (smallImage) { + if ((smallImageFile != null) && (smallImageBytes != null)) { + imageLocalService.updateImage(smallImageId, smallImageBytes); + } + } + else { + imageLocalService.deleteImage(smallImageId); + } + + // Medium image + + if (mediumImage) { + if ((mediumImageFile != null) && (mediumImageBytes != null)) { + imageLocalService.updateImage(mediumImageId, mediumImageBytes); + } + } + else { + imageLocalService.deleteImage(mediumImageId); + } + + // Large image + + if (largeImage) { + if ((largeImageFile != null) && (largeImageBytes != null)) { + imageLocalService.updateImage(largeImageId, largeImageBytes); + } + } + else { + imageLocalService.deleteImage(largeImageId); + } + } + + protected void validate( + long companyId, long itemId, String sku, String name, + boolean smallImage, String smallImageURL, File smallImageFile, + byte[] smallImageBytes, boolean mediumImage, String mediumImageURL, + File mediumImageFile, byte[] mediumImageBytes, boolean largeImage, + String largeImageURL, File largeImageFile, byte[] largeImageBytes) + throws PortalException, SystemException { + + if (Validator.isNull(sku)) { + throw new ItemSKUException(); + } + + ShoppingItem item = shoppingItemPersistence.fetchByC_S(companyId, sku); + + if (item != null) { + if (itemId > 0) { + if (item.getItemId() != itemId) { + throw new DuplicateItemSKUException(); + } + } + else { + throw new DuplicateItemSKUException(); + } + } + + if (Validator.isNull(name)) { + throw new ItemNameException(); + } + + String[] imageExtensions = PrefsPropsUtil.getStringArray( + PropsKeys.SHOPPING_IMAGE_EXTENSIONS, StringPool.COMMA); + + // Small image + + if (smallImage && Validator.isNull(smallImageURL) && + smallImageFile != null && smallImageBytes != null) { + + String smallImageName = smallImageFile.getName(); + + if (smallImageName != null) { + boolean validSmallImageExtension = false; + + for (int i = 0; i < imageExtensions.length; i++) { + if (StringPool.STAR.equals(imageExtensions[i]) || + StringUtil.endsWith( + smallImageName, imageExtensions[i])) { + + validSmallImageExtension = true; + + break; + } + } + + if (!validSmallImageExtension) { + throw new ItemSmallImageNameException(smallImageName); + } + } + + long smallImageMaxSize = PrefsPropsUtil.getLong( + PropsKeys.SHOPPING_IMAGE_MEDIUM_MAX_SIZE); + + if ((smallImageMaxSize > 0) && + ((smallImageBytes == null) || + (smallImageBytes.length > smallImageMaxSize))) { + + throw new ItemSmallImageSizeException(); + } + } + + // Medium image + + if (mediumImage && Validator.isNull(mediumImageURL) && + mediumImageFile != null && mediumImageBytes != null) { + + String mediumImageName = mediumImageFile.getName(); + + if (mediumImageName != null) { + boolean validMediumImageExtension = false; + + for (int i = 0; i < imageExtensions.length; i++) { + if (StringPool.STAR.equals(imageExtensions[i]) || + StringUtil.endsWith( + mediumImageName, imageExtensions[i])) { + + validMediumImageExtension = true; + + break; + } + } + + if (!validMediumImageExtension) { + throw new ItemMediumImageNameException(mediumImageName); + } + } + + long mediumImageMaxSize = PrefsPropsUtil.getLong( + PropsKeys.SHOPPING_IMAGE_MEDIUM_MAX_SIZE); + + if ((mediumImageMaxSize > 0) && + ((mediumImageBytes == null) || + (mediumImageBytes.length > mediumImageMaxSize))) { + + throw new ItemMediumImageSizeException(); + } + } + + // Large image + + if (largeImage && Validator.isNull(largeImageURL) && + largeImageFile != null && largeImageBytes != null) { + + String largeImageName = largeImageFile.getName(); + + if (largeImageName != null) { + boolean validLargeImageExtension = false; + + for (int i = 0; i < imageExtensions.length; i++) { + if (StringPool.STAR.equals(imageExtensions[i]) || + StringUtil.endsWith( + largeImageName, imageExtensions[i])) { + + validLargeImageExtension = true; + + break; + } + } + + if (!validLargeImageExtension) { + throw new ItemLargeImageNameException(largeImageName); + } + } + + long largeImageMaxSize = PrefsPropsUtil.getLong( + PropsKeys.SHOPPING_IMAGE_LARGE_MAX_SIZE); + + if ((largeImageMaxSize > 0) && + ((largeImageBytes == null) || + (largeImageBytes.length > largeImageMaxSize))) { + + throw new ItemLargeImageSizeException(); + } + } + } + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingOrderLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingOrderLocalServiceImpl.java index 3d7958bfccf6e0..5e367e2f62a482 100644 --- a/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingOrderLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/shopping/service/impl/ShoppingOrderLocalServiceImpl.java @@ -541,9 +541,8 @@ public ShoppingOrder updateLatestOrder( billingState, billingZip, billingCountry, billingPhone, shipToBilling, shippingFirstName, shippingLastName, shippingEmailAddress, shippingCompany, shippingStreet, shippingCity, - shippingState, shippingZip, shippingCountry, shippingPhone, - ccName, ccType, ccNumber, ccExpMonth, ccExpYear, ccVerNumber, - comments); + shippingState, shippingZip, shippingCountry, shippingPhone, ccName, + ccType, ccNumber, ccExpMonth, ccExpYear, ccVerNumber, comments); } public ShoppingOrder updateOrder( diff --git a/portal-impl/src/com/liferay/portlet/shopping/util/ShoppingUtil.java b/portal-impl/src/com/liferay/portlet/shopping/util/ShoppingUtil.java index 07797f9f349039..2ec7356367716f 100644 --- a/portal-impl/src/com/liferay/portlet/shopping/util/ShoppingUtil.java +++ b/portal-impl/src/com/liferay/portlet/shopping/util/ShoppingUtil.java @@ -993,8 +993,8 @@ public static boolean isInStock(ShoppingItem item) { } public static boolean isInStock( - ShoppingItem item, ShoppingItemField[] itemFields, - String[] fieldsArray, Integer orderedQuantity) { + ShoppingItem item, ShoppingItemField[] itemFields, String[] fieldsArray, + Integer orderedQuantity) { if (!item.isFields()) { int stockQuantity = item.getStockQuantity(); diff --git a/portal-impl/src/com/liferay/portlet/sites/action/ReplyMembershipRequestAction.java b/portal-impl/src/com/liferay/portlet/sites/action/ReplyMembershipRequestAction.java index 6096da42519d9f..a1b3a49db8b1ce 100644 --- a/portal-impl/src/com/liferay/portlet/sites/action/ReplyMembershipRequestAction.java +++ b/portal-impl/src/com/liferay/portlet/sites/action/ReplyMembershipRequestAction.java @@ -74,8 +74,7 @@ public void processAction( membershipRequestId); LiveUsers.joinGroup( - themeDisplay.getCompanyId(), - membershipRequest.getGroupId(), + themeDisplay.getCompanyId(), membershipRequest.getGroupId(), new long[] {membershipRequest.getUserId()}); } diff --git a/portal-impl/src/com/liferay/portlet/sites/util/SitesUtil.java b/portal-impl/src/com/liferay/portlet/sites/util/SitesUtil.java index 7fe4312da2bb5f..3535fe9e9b4582 100644 --- a/portal-impl/src/com/liferay/portlet/sites/util/SitesUtil.java +++ b/portal-impl/src/com/liferay/portlet/sites/util/SitesUtil.java @@ -165,13 +165,12 @@ public static void applyLayoutPrototype( targetLayout = LayoutLocalServiceUtil.updateLayout( targetLayout.getGroupId(), targetLayout.isPrivateLayout(), - targetLayout.getLayoutId(), - targetLayout.getParentLayoutId(), targetLayout.getNameMap(), - targetLayout.getTitleMap(), targetLayout.getDescriptionMap(), - targetLayout.getKeywordsMap(), targetLayout.getRobotsMap(), - layoutPrototypeLayout.getType(), targetLayout.getHidden(), - targetLayout.getFriendlyURL(), targetLayout.getIconImage(), null, - serviceContext); + targetLayout.getLayoutId(), targetLayout.getParentLayoutId(), + targetLayout.getNameMap(), targetLayout.getTitleMap(), + targetLayout.getDescriptionMap(), targetLayout.getKeywordsMap(), + targetLayout.getRobotsMap(), layoutPrototypeLayout.getType(), + targetLayout.getHidden(), targetLayout.getFriendlyURL(), + targetLayout.getIconImage(), null, serviceContext); targetLayout = LayoutLocalServiceUtil.updateLayout( targetLayout.getGroupId(), targetLayout.isPrivateLayout(), @@ -493,8 +492,8 @@ public static File exportLayoutSetPrototype( serviceContext); return LayoutLocalServiceUtil.exportLayoutsAsFile( - layoutSet.getGroupId(), layoutSet.isPrivateLayout(), - null, parameterMap, null, null); + layoutSet.getGroupId(), layoutSet.isPrivateLayout(), null, + parameterMap, null, null); } public static Map getLayoutSetPrototypeParameters( @@ -578,8 +577,8 @@ public static void importLayoutSetPrototype( parameterMap, layoutSet, serviceContext); LayoutServiceUtil.importLayouts( - layoutSet.getGroupId(), layoutSet.isPrivateLayout(), - parameterMap, inputStream); + layoutSet.getGroupId(), layoutSet.isPrivateLayout(), parameterMap, + inputStream); } public static boolean isLayoutDeleteable(Layout layout) { @@ -1144,8 +1143,8 @@ protected static void importLayoutSetPrototype( Group layoutSetPrototypeGroup = layoutSetPrototype.getGroup(); file = LayoutLocalServiceUtil.exportLayoutsAsFile( - layoutSetPrototypeGroup.getGroupId(), true, null, - parameterMap, null, null); + layoutSetPrototypeGroup.getGroupId(), true, null, parameterMap, + null, null); newFile = true; } diff --git a/portal-impl/src/com/liferay/portlet/sitesadmin/SiteMembershipsControlPanelEntry.java b/portal-impl/src/com/liferay/portlet/sitesadmin/SiteMembershipsControlPanelEntry.java index 1e18c8ae688def..56470811f21fc5 100644 --- a/portal-impl/src/com/liferay/portlet/sitesadmin/SiteMembershipsControlPanelEntry.java +++ b/portal-impl/src/com/liferay/portlet/sitesadmin/SiteMembershipsControlPanelEntry.java @@ -50,8 +50,8 @@ public boolean isVisible( if (scopeGroup.isCompany() || scopeGroup.isUser() || !GroupPermissionUtil.contains( - themeDisplay.getPermissionChecker(), - scopeGroup.getGroupId(), ActionKeys.ASSIGN_MEMBERS)) { + themeDisplay.getPermissionChecker(), scopeGroup.getGroupId(), + ActionKeys.ASSIGN_MEMBERS)) { return false; } diff --git a/portal-impl/src/com/liferay/portlet/sitesadmin/SiteSettingsControlPanelEntry.java b/portal-impl/src/com/liferay/portlet/sitesadmin/SiteSettingsControlPanelEntry.java index 4752671bc9614d..04f2f00b672ecd 100644 --- a/portal-impl/src/com/liferay/portlet/sitesadmin/SiteSettingsControlPanelEntry.java +++ b/portal-impl/src/com/liferay/portlet/sitesadmin/SiteSettingsControlPanelEntry.java @@ -50,8 +50,8 @@ public boolean isVisible( if (scopeGroup.isCompany() || scopeGroup.isUser() || !GroupPermissionUtil.contains( - themeDisplay.getPermissionChecker(), - scopeGroup.getGroupId(), ActionKeys.UPDATE)) { + themeDisplay.getPermissionChecker(), scopeGroup.getGroupId(), + ActionKeys.UPDATE)) { return false; } diff --git a/portal-impl/src/com/liferay/portlet/social/service/impl/SocialRequestLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/social/service/impl/SocialRequestLocalServiceImpl.java index c5cebf65b58b98..48004a9e80a75b 100644 --- a/portal-impl/src/com/liferay/portlet/social/service/impl/SocialRequestLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/social/service/impl/SocialRequestLocalServiceImpl.java @@ -1,443 +1,443 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portlet.social.service.impl; - -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.model.User; -import com.liferay.portal.theme.ThemeDisplay; -import com.liferay.portal.util.PortalUtil; -import com.liferay.portlet.social.NoSuchRequestException; -import com.liferay.portlet.social.RequestUserIdException; -import com.liferay.portlet.social.model.SocialRequest; -import com.liferay.portlet.social.model.SocialRequestConstants; -import com.liferay.portlet.social.service.base.SocialRequestLocalServiceBaseImpl; - -import java.util.List; - -/** - * The social request local service responsible for handling social requests - * (e.g. friend requests). - * - * @author Brian Wing Shun Chan - */ -public class SocialRequestLocalServiceImpl - extends SocialRequestLocalServiceBaseImpl { - - /** - * Adds a social request to the database. - * - *

- * In order to add a social request, both the requesting user and the - * receiving user must be from the same company and neither of them can be - * the default user. - *

- * - * @param userId the primary key of the requesting user - * @param groupId the primary key of the group - * @param className the class name of the asset that is the subject of the - * request - * @param classPK the primary key of the asset that is the subject of the - * request - * @param type the request's type - * @param extraData the extra data regarding the request - * @param receiverUserId the primary key of the user receiving the request - * @return the social request - * @throws PortalException if the users could not be found, if the users - * were not from the same company, or if either of the users was the - * default user - * @throws SystemException if a system exception occurred - */ - public SocialRequest addRequest( - long userId, long groupId, String className, long classPK, - int type, String extraData, long receiverUserId) - throws PortalException, SystemException { - - User user = userPersistence.findByPrimaryKey(userId); - long classNameId = PortalUtil.getClassNameId(className); - User receiverUser = userPersistence.findByPrimaryKey(receiverUserId); - long now = System.currentTimeMillis(); - - if ((userId == receiverUserId) || (user.isDefaultUser()) || - (receiverUser.isDefaultUser()) || - (user.getCompanyId() != receiverUser.getCompanyId())) { - - throw new RequestUserIdException(); - } - - try { - socialRequestPersistence.removeByU_C_C_T_R( - userId, classNameId, classPK, type, receiverUserId); - } - catch (NoSuchRequestException nsre) { - } - - long requestId = counterLocalService.increment( - SocialRequest.class.getName()); - - SocialRequest request = socialRequestPersistence.create(requestId); - - request.setGroupId(groupId); - request.setCompanyId(user.getCompanyId()); - request.setUserId(user.getUserId()); - request.setCreateDate(now); - request.setModifiedDate(now); - request.setClassNameId(classNameId); - request.setClassPK(classPK); - request.setType(type); - request.setExtraData(extraData); - request.setReceiverUserId(receiverUserId); - request.setStatus(SocialRequestConstants.STATUS_PENDING); - - socialRequestPersistence.update(request, false); - - return request; - } - - /** - * Removes all the social requests for the receiving user. - * - * @param receiverUserId the primary key of the receiving user - * @throws SystemException if a system exception occurred - */ - public void deleteReceiverUserRequests(long receiverUserId) - throws SystemException { - - List requests = - socialRequestPersistence.findByReceiverUserId(receiverUserId); - - for (SocialRequest request : requests) { - deleteRequest(request); - } - } - - /** - * Removes the social request identified by its primary key from the - * database. - * - * @param requestId the primary key of the social request - * @throws PortalException if the social request could not be found - * @throws SystemException if a system exception occurred - */ - public void deleteRequest(long requestId) - throws PortalException, SystemException { - - SocialRequest request = socialRequestPersistence.findByPrimaryKey( - requestId); - - deleteRequest(request); - } - - /** - * Removes the social request from the database. - * - * @param request the social request to be removed - * @throws SystemException if a system exception occurred - */ - public void deleteRequest(SocialRequest request) throws SystemException { - socialRequestPersistence.remove(request); - } - - /** - * Removes all the social requests for the requesting user. - * - * @param userId the primary key of the requesting user - * @throws SystemException if a system exception occurred - */ - public void deleteUserRequests(long userId) throws SystemException { - List requests = socialRequestPersistence.findByUserId( - userId); - - for (SocialRequest request : requests) { - deleteRequest(request); - } - } - - /** - * Returns a range of all the social requests for the receiving user. - * - *

- * Useful when paginating results. Returns a maximum of end - - * start instances. start and end are not - * primary keys, they are indexes in the result set. Thus, 0 - * refers to the first result in the set. Setting both start - * and end to {@link - * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full - * result set. - *

- * - * @param receiverUserId the primary key of the receiving user - * @param start the lower bound of the range of results - * @param end the upper bound of the range of results (not inclusive) - * @return the range of matching social requests - * @throws SystemException if a system exception occurred - */ - public List getReceiverUserRequests( - long receiverUserId, int start, int end) - throws SystemException { - - return socialRequestPersistence.findByReceiverUserId( - receiverUserId, start, end); - } - - /** - * Returns a range of all the social requests with the given status for the - * receiving user. - * - *

- * Useful when paginating results. Returns a maximum of end - - * start instances. start and end are not - * primary keys, they are indexes in the result set. Thus, 0 - * refers to the first result in the set. Setting both start - * and end to {@link - * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full - * result set. - *

- * - * @param receiverUserId the primary key of the receiving user - * @param status the social request's status - * @param start the lower bound of the range of results - * @param end the upper bound of the range of results (not inclusive) - * @return the range of matching social requests - * @throws SystemException if a system exception occurred - */ - public List getReceiverUserRequests( - long receiverUserId, int status, int start, int end) - throws SystemException { - - return socialRequestPersistence.findByR_S( - receiverUserId, status, start, end); - } - - /** - * Returns the number of social requests for the receiving user. - * - * @param receiverUserId the primary key of the receiving user - * @return the number of matching social requests - * @throws SystemException if a system exception occurred - */ - public int getReceiverUserRequestsCount(long receiverUserId) - throws SystemException { - - return socialRequestPersistence.countByReceiverUserId(receiverUserId); - } - - /** - * Returns the number of social requests with the given status for the - * receiving user. - * - * @param receiverUserId the primary key of the receiving user - * @param status the social request's status - * @return the number of matching social requests - * @throws SystemException if a system exception occurred - */ - public int getReceiverUserRequestsCount(long receiverUserId, int status) - throws SystemException { - - return socialRequestPersistence.countByR_S(receiverUserId, status); - } - - /** - * Returns a range of all the social requests for the requesting user. - * - *

- * Useful when paginating results. Returns a maximum of end - - * start instances. start and end are not - * primary keys, they are indexes in the result set. Thus, 0 - * refers to the first result in the set. Setting both start - * and end to {@link - * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full - * result set. - *

- * - * @param userId the primary key of the requesting user - * @param start the lower bound of the range of results - * @param end the upper bound of the range of results (not inclusive) - * @return the range of matching social requests - * @throws SystemException if a system exception occurred - */ - public List getUserRequests(long userId, int start, int end) - throws SystemException { - - return socialRequestPersistence.findByUserId(userId, start, end); - } - - /** - * Returns a range of all the social requests with the given status for the - * requesting user. - * - *

- * Useful when paginating results. Returns a maximum of end - - * start instances. start and end are not - * primary keys, they are indexes in the result set. Thus, 0 - * refers to the first result in the set. Setting both start - * and end to {@link - * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full - * result set. - *

- * - * @param userId the primary key of the requesting user - * @param status the social request's status - * @param start the lower bound of the range of results - * @param end the upper bound of the range of results (not inclusive) - * @return the range of matching social requests - * @throws SystemException if a system exception occurred - */ - public List getUserRequests( - long userId, int status, int start, int end) - throws SystemException { - - return socialRequestPersistence.findByU_S(userId, status, start, end); - } - - /** - * Returns the number of social requests for the requesting user. - * - * @param userId the primary key of the requesting user - * @return the number of matching social requests - * @throws SystemException if a system exception occurred - */ - public int getUserRequestsCount(long userId) throws SystemException { - return socialRequestPersistence.countByUserId(userId); - } - - /** - * Returns the number of social requests with the given status for the - * requesting user. - * - * @param userId the primary key of the requesting user - * @param status the social request's status - * @return the number of matching social request - * @throws SystemException if a system exception occurred - */ - public int getUserRequestsCount(long userId, int status) - throws SystemException { - - return socialRequestPersistence.countByU_S(userId, status); - } - - /** - * Returns true if a matching social requests exists in the - * database. - * - * @param userId the primary key of the requesting user - * @param className the class name of the asset that is the subject of the - * request - * @param classPK the primary key of the asset that is the subject of the - * request - * @param type the request's type - * @param status the social request's status - * @return true if the request exists; false - * otherwise - * @throws SystemException if a system exception occurred - */ - public boolean hasRequest( - long userId, String className, long classPK, int type, int status) - throws SystemException { - - long classNameId = PortalUtil.getClassNameId(className); - - if (socialRequestPersistence.countByU_C_C_T_S( - userId, classNameId, classPK, type, status) <= 0) { - - return false; - } - else { - return true; - } - } - - /** - * Returns true if a matching social request exists in the - * database. - * - * @param userId the primary key of the requesting user - * @param className the class name of the asset that is the subject of the - * request - * @param classPK the primary key of the asset that is the subject of the - * request - * @param type the request's type - * @param receiverUserId the primary key of the receiving user - * @param status the social request's status - * @return true if the social request exists; - * false otherwise - * @throws SystemException if a system exception occurred - */ - public boolean hasRequest( - long userId, String className, long classPK, int type, - long receiverUserId, int status) - throws SystemException { - - long classNameId = PortalUtil.getClassNameId(className); - - SocialRequest socialRequest = socialRequestPersistence.fetchByU_C_C_T_R( - userId, classNameId, classPK, type, receiverUserId); - - if ((socialRequest == null) || (socialRequest.getStatus() != status)) { - return false; - } - else { - return true; - } - } - - /** - * Updates the social request replacing its status. - * - *

- * If the status is updated to {@link - * com.liferay.portlet.social.model.SocialRequestConstants#STATUS_CONFIRM} - * then {@link - * com.liferay.portlet.social.service.SocialRequestInterpreterLocalService#processConfirmation( - * SocialRequest, ThemeDisplay)} is called. If the status is updated to - * {@link - * com.liferay.portlet.social.model.SocialRequestConstants#STATUS_IGNORE} - * then {@link - * com.liferay.portlet.social.service.SocialRequestInterpreterLocalService#processRejection( - * SocialRequest, ThemeDisplay)} is called. - *

- * - * @param requestId the primary key of the social request - * @param status the new status - * @param themeDisplay the theme display - * @return the updated social request - * @throws PortalException if the social request could not be found - * @throws SystemException if a system exception occurred - */ - public SocialRequest updateRequest( - long requestId, int status, ThemeDisplay themeDisplay) - throws PortalException, SystemException { - - SocialRequest request = socialRequestPersistence.findByPrimaryKey( - requestId); - - request.setModifiedDate(System.currentTimeMillis()); - request.setStatus(status); - - socialRequestPersistence.update(request, false); - - if (status == SocialRequestConstants.STATUS_CONFIRM) { - socialRequestInterpreterLocalService.processConfirmation( - request, themeDisplay); - } - else if (status == SocialRequestConstants.STATUS_IGNORE) { - socialRequestInterpreterLocalService.processRejection( - request, themeDisplay); - } - - return request; - } - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portlet.social.service.impl; + +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.model.User; +import com.liferay.portal.theme.ThemeDisplay; +import com.liferay.portal.util.PortalUtil; +import com.liferay.portlet.social.NoSuchRequestException; +import com.liferay.portlet.social.RequestUserIdException; +import com.liferay.portlet.social.model.SocialRequest; +import com.liferay.portlet.social.model.SocialRequestConstants; +import com.liferay.portlet.social.service.base.SocialRequestLocalServiceBaseImpl; + +import java.util.List; + +/** + * The social request local service responsible for handling social requests + * (e.g. friend requests). + * + * @author Brian Wing Shun Chan + */ +public class SocialRequestLocalServiceImpl + extends SocialRequestLocalServiceBaseImpl { + + /** + * Adds a social request to the database. + * + *

+ * In order to add a social request, both the requesting user and the + * receiving user must be from the same company and neither of them can be + * the default user. + *

+ * + * @param userId the primary key of the requesting user + * @param groupId the primary key of the group + * @param className the class name of the asset that is the subject of the + * request + * @param classPK the primary key of the asset that is the subject of the + * request + * @param type the request's type + * @param extraData the extra data regarding the request + * @param receiverUserId the primary key of the user receiving the request + * @return the social request + * @throws PortalException if the users could not be found, if the users + * were not from the same company, or if either of the users was the + * default user + * @throws SystemException if a system exception occurred + */ + public SocialRequest addRequest( + long userId, long groupId, String className, long classPK, int type, + String extraData, long receiverUserId) + throws PortalException, SystemException { + + User user = userPersistence.findByPrimaryKey(userId); + long classNameId = PortalUtil.getClassNameId(className); + User receiverUser = userPersistence.findByPrimaryKey(receiverUserId); + long now = System.currentTimeMillis(); + + if ((userId == receiverUserId) || (user.isDefaultUser()) || + (receiverUser.isDefaultUser()) || + (user.getCompanyId() != receiverUser.getCompanyId())) { + + throw new RequestUserIdException(); + } + + try { + socialRequestPersistence.removeByU_C_C_T_R( + userId, classNameId, classPK, type, receiverUserId); + } + catch (NoSuchRequestException nsre) { + } + + long requestId = counterLocalService.increment( + SocialRequest.class.getName()); + + SocialRequest request = socialRequestPersistence.create(requestId); + + request.setGroupId(groupId); + request.setCompanyId(user.getCompanyId()); + request.setUserId(user.getUserId()); + request.setCreateDate(now); + request.setModifiedDate(now); + request.setClassNameId(classNameId); + request.setClassPK(classPK); + request.setType(type); + request.setExtraData(extraData); + request.setReceiverUserId(receiverUserId); + request.setStatus(SocialRequestConstants.STATUS_PENDING); + + socialRequestPersistence.update(request, false); + + return request; + } + + /** + * Removes all the social requests for the receiving user. + * + * @param receiverUserId the primary key of the receiving user + * @throws SystemException if a system exception occurred + */ + public void deleteReceiverUserRequests(long receiverUserId) + throws SystemException { + + List requests = + socialRequestPersistence.findByReceiverUserId(receiverUserId); + + for (SocialRequest request : requests) { + deleteRequest(request); + } + } + + /** + * Removes the social request identified by its primary key from the + * database. + * + * @param requestId the primary key of the social request + * @throws PortalException if the social request could not be found + * @throws SystemException if a system exception occurred + */ + public void deleteRequest(long requestId) + throws PortalException, SystemException { + + SocialRequest request = socialRequestPersistence.findByPrimaryKey( + requestId); + + deleteRequest(request); + } + + /** + * Removes the social request from the database. + * + * @param request the social request to be removed + * @throws SystemException if a system exception occurred + */ + public void deleteRequest(SocialRequest request) throws SystemException { + socialRequestPersistence.remove(request); + } + + /** + * Removes all the social requests for the requesting user. + * + * @param userId the primary key of the requesting user + * @throws SystemException if a system exception occurred + */ + public void deleteUserRequests(long userId) throws SystemException { + List requests = socialRequestPersistence.findByUserId( + userId); + + for (SocialRequest request : requests) { + deleteRequest(request); + } + } + + /** + * Returns a range of all the social requests for the receiving user. + * + *

+ * Useful when paginating results. Returns a maximum of end - + * start instances. start and end are not + * primary keys, they are indexes in the result set. Thus, 0 + * refers to the first result in the set. Setting both start + * and end to {@link + * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full + * result set. + *

+ * + * @param receiverUserId the primary key of the receiving user + * @param start the lower bound of the range of results + * @param end the upper bound of the range of results (not inclusive) + * @return the range of matching social requests + * @throws SystemException if a system exception occurred + */ + public List getReceiverUserRequests( + long receiverUserId, int start, int end) + throws SystemException { + + return socialRequestPersistence.findByReceiverUserId( + receiverUserId, start, end); + } + + /** + * Returns a range of all the social requests with the given status for the + * receiving user. + * + *

+ * Useful when paginating results. Returns a maximum of end - + * start instances. start and end are not + * primary keys, they are indexes in the result set. Thus, 0 + * refers to the first result in the set. Setting both start + * and end to {@link + * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full + * result set. + *

+ * + * @param receiverUserId the primary key of the receiving user + * @param status the social request's status + * @param start the lower bound of the range of results + * @param end the upper bound of the range of results (not inclusive) + * @return the range of matching social requests + * @throws SystemException if a system exception occurred + */ + public List getReceiverUserRequests( + long receiverUserId, int status, int start, int end) + throws SystemException { + + return socialRequestPersistence.findByR_S( + receiverUserId, status, start, end); + } + + /** + * Returns the number of social requests for the receiving user. + * + * @param receiverUserId the primary key of the receiving user + * @return the number of matching social requests + * @throws SystemException if a system exception occurred + */ + public int getReceiverUserRequestsCount(long receiverUserId) + throws SystemException { + + return socialRequestPersistence.countByReceiverUserId(receiverUserId); + } + + /** + * Returns the number of social requests with the given status for the + * receiving user. + * + * @param receiverUserId the primary key of the receiving user + * @param status the social request's status + * @return the number of matching social requests + * @throws SystemException if a system exception occurred + */ + public int getReceiverUserRequestsCount(long receiverUserId, int status) + throws SystemException { + + return socialRequestPersistence.countByR_S(receiverUserId, status); + } + + /** + * Returns a range of all the social requests for the requesting user. + * + *

+ * Useful when paginating results. Returns a maximum of end - + * start instances. start and end are not + * primary keys, they are indexes in the result set. Thus, 0 + * refers to the first result in the set. Setting both start + * and end to {@link + * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full + * result set. + *

+ * + * @param userId the primary key of the requesting user + * @param start the lower bound of the range of results + * @param end the upper bound of the range of results (not inclusive) + * @return the range of matching social requests + * @throws SystemException if a system exception occurred + */ + public List getUserRequests(long userId, int start, int end) + throws SystemException { + + return socialRequestPersistence.findByUserId(userId, start, end); + } + + /** + * Returns a range of all the social requests with the given status for the + * requesting user. + * + *

+ * Useful when paginating results. Returns a maximum of end - + * start instances. start and end are not + * primary keys, they are indexes in the result set. Thus, 0 + * refers to the first result in the set. Setting both start + * and end to {@link + * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full + * result set. + *

+ * + * @param userId the primary key of the requesting user + * @param status the social request's status + * @param start the lower bound of the range of results + * @param end the upper bound of the range of results (not inclusive) + * @return the range of matching social requests + * @throws SystemException if a system exception occurred + */ + public List getUserRequests( + long userId, int status, int start, int end) + throws SystemException { + + return socialRequestPersistence.findByU_S(userId, status, start, end); + } + + /** + * Returns the number of social requests for the requesting user. + * + * @param userId the primary key of the requesting user + * @return the number of matching social requests + * @throws SystemException if a system exception occurred + */ + public int getUserRequestsCount(long userId) throws SystemException { + return socialRequestPersistence.countByUserId(userId); + } + + /** + * Returns the number of social requests with the given status for the + * requesting user. + * + * @param userId the primary key of the requesting user + * @param status the social request's status + * @return the number of matching social request + * @throws SystemException if a system exception occurred + */ + public int getUserRequestsCount(long userId, int status) + throws SystemException { + + return socialRequestPersistence.countByU_S(userId, status); + } + + /** + * Returns true if a matching social requests exists in the + * database. + * + * @param userId the primary key of the requesting user + * @param className the class name of the asset that is the subject of the + * request + * @param classPK the primary key of the asset that is the subject of the + * request + * @param type the request's type + * @param status the social request's status + * @return true if the request exists; false + * otherwise + * @throws SystemException if a system exception occurred + */ + public boolean hasRequest( + long userId, String className, long classPK, int type, int status) + throws SystemException { + + long classNameId = PortalUtil.getClassNameId(className); + + if (socialRequestPersistence.countByU_C_C_T_S( + userId, classNameId, classPK, type, status) <= 0) { + + return false; + } + else { + return true; + } + } + + /** + * Returns true if a matching social request exists in the + * database. + * + * @param userId the primary key of the requesting user + * @param className the class name of the asset that is the subject of the + * request + * @param classPK the primary key of the asset that is the subject of the + * request + * @param type the request's type + * @param receiverUserId the primary key of the receiving user + * @param status the social request's status + * @return true if the social request exists; + * false otherwise + * @throws SystemException if a system exception occurred + */ + public boolean hasRequest( + long userId, String className, long classPK, int type, + long receiverUserId, int status) + throws SystemException { + + long classNameId = PortalUtil.getClassNameId(className); + + SocialRequest socialRequest = socialRequestPersistence.fetchByU_C_C_T_R( + userId, classNameId, classPK, type, receiverUserId); + + if ((socialRequest == null) || (socialRequest.getStatus() != status)) { + return false; + } + else { + return true; + } + } + + /** + * Updates the social request replacing its status. + * + *

+ * If the status is updated to {@link + * com.liferay.portlet.social.model.SocialRequestConstants#STATUS_CONFIRM} + * then {@link + * com.liferay.portlet.social.service.SocialRequestInterpreterLocalService#processConfirmation( + * SocialRequest, ThemeDisplay)} is called. If the status is updated to + * {@link + * com.liferay.portlet.social.model.SocialRequestConstants#STATUS_IGNORE} + * then {@link + * com.liferay.portlet.social.service.SocialRequestInterpreterLocalService#processRejection( + * SocialRequest, ThemeDisplay)} is called. + *

+ * + * @param requestId the primary key of the social request + * @param status the new status + * @param themeDisplay the theme display + * @return the updated social request + * @throws PortalException if the social request could not be found + * @throws SystemException if a system exception occurred + */ + public SocialRequest updateRequest( + long requestId, int status, ThemeDisplay themeDisplay) + throws PortalException, SystemException { + + SocialRequest request = socialRequestPersistence.findByPrimaryKey( + requestId); + + request.setModifiedDate(System.currentTimeMillis()); + request.setStatus(status); + + socialRequestPersistence.update(request, false); + + if (status == SocialRequestConstants.STATUS_CONFIRM) { + socialRequestInterpreterLocalService.processConfirmation( + request, themeDisplay); + } + else if (status == SocialRequestConstants.STATUS_IGNORE) { + socialRequestInterpreterLocalService.processRejection( + request, themeDisplay); + } + + return request; + } + } \ No newline at end of file diff --git a/portal-impl/src/com/liferay/portlet/softwarecatalog/service/impl/SCFrameworkVersionLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/softwarecatalog/service/impl/SCFrameworkVersionLocalServiceImpl.java index 1c74ded71e3938..b6a55e1bfb0389 100644 --- a/portal-impl/src/com/liferay/portlet/softwarecatalog/service/impl/SCFrameworkVersionLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/softwarecatalog/service/impl/SCFrameworkVersionLocalServiceImpl.java @@ -107,8 +107,8 @@ public void addFrameworkVersionResources( } public void addFrameworkVersionResources( - SCFrameworkVersion frameworkVersion, - boolean addGroupPermissions, boolean addGuestPermissions) + SCFrameworkVersion frameworkVersion, boolean addGroupPermissions, + boolean addGuestPermissions) throws PortalException, SystemException { resourceLocalService.addResources( diff --git a/portal-impl/src/com/liferay/portlet/softwarecatalog/service/impl/SCProductEntryServiceImpl.java b/portal-impl/src/com/liferay/portlet/softwarecatalog/service/impl/SCProductEntryServiceImpl.java index 11969bc582872b..8d71393f70dd84 100644 --- a/portal-impl/src/com/liferay/portlet/softwarecatalog/service/impl/SCProductEntryServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/softwarecatalog/service/impl/SCProductEntryServiceImpl.java @@ -44,9 +44,9 @@ public SCProductEntry addProductEntry( ActionKeys.ADD_PRODUCT_ENTRY); return scProductEntryLocalService.addProductEntry( - getUserId(), name, type, tags, shortDescription, - longDescription, pageURL, author, repoGroupId, repoArtifactId, - licenseIds, thumbnails, fullImages, serviceContext); + getUserId(), name, type, tags, shortDescription, longDescription, + pageURL, author, repoGroupId, repoArtifactId, licenseIds, + thumbnails, fullImages, serviceContext); } public void deleteProductEntry(long productEntryId) diff --git a/portal-impl/src/com/liferay/portlet/usersadmin/action/EditOrganizationAction.java b/portal-impl/src/com/liferay/portlet/usersadmin/action/EditOrganizationAction.java index d699639b09cfc2..3aa9ea6c59acf4 100644 --- a/portal-impl/src/com/liferay/portlet/usersadmin/action/EditOrganizationAction.java +++ b/portal-impl/src/com/liferay/portlet/usersadmin/action/EditOrganizationAction.java @@ -237,10 +237,9 @@ protected Organization updateOrganization(ActionRequest actionRequest) // Update organization organization = OrganizationServiceUtil.updateOrganization( - organizationId, parentOrganizationId, name, type, - recursable, regionId, countryId, statusId, comments, site, - addresses, emailAddresses, orgLabors, phones, websites, - serviceContext); + organizationId, parentOrganizationId, name, type, recursable, + regionId, countryId, statusId, comments, site, addresses, + emailAddresses, orgLabors, phones, websites, serviceContext); boolean deleteLogo = ParamUtil.getBoolean( actionRequest, "deleteLogo"); diff --git a/portal-impl/src/com/liferay/portlet/wiki/asset/WikiPageAssetRendererFactory.java b/portal-impl/src/com/liferay/portlet/wiki/asset/WikiPageAssetRendererFactory.java index 1e95ebdbc60303..ef662693418b16 100644 --- a/portal-impl/src/com/liferay/portlet/wiki/asset/WikiPageAssetRendererFactory.java +++ b/portal-impl/src/com/liferay/portlet/wiki/asset/WikiPageAssetRendererFactory.java @@ -57,8 +57,8 @@ public AssetRenderer getAssetRenderer(long classPK, int type) WikiPageResourceLocalServiceUtil.getPageResource(classPK); page = WikiPageLocalServiceUtil.getPage( - wikiPageResource.getNodeId(), - wikiPageResource.getTitle(), null); + wikiPageResource.getNodeId(), wikiPageResource.getTitle(), + null); } } diff --git a/portal-impl/src/com/liferay/portlet/wiki/importers/mediawiki/MediaWikiImporter.java b/portal-impl/src/com/liferay/portlet/wiki/importers/mediawiki/MediaWikiImporter.java index 923177aef1289c..72eb49f3d7227e 100644 --- a/portal-impl/src/com/liferay/portlet/wiki/importers/mediawiki/MediaWikiImporter.java +++ b/portal-impl/src/com/liferay/portlet/wiki/importers/mediawiki/MediaWikiImporter.java @@ -471,8 +471,8 @@ protected void processRegularPages( try { importPage( - userId, author, node, title, content, summary, - usersMap, strictImportMode); + userId, author, node, title, content, summary, usersMap, + strictImportMode); } catch (Exception e) { if (_log.isWarnEnabled()) { diff --git a/portal-impl/src/com/liferay/portlet/wiki/service/impl/WikiPageLocalServiceImpl.java b/portal-impl/src/com/liferay/portlet/wiki/service/impl/WikiPageLocalServiceImpl.java index 997304c4b59ac5..63a8dcd67ac7e5 100644 --- a/portal-impl/src/com/liferay/portlet/wiki/service/impl/WikiPageLocalServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/wiki/service/impl/WikiPageLocalServiceImpl.java @@ -202,8 +202,7 @@ public WikiPage addPage( WorkflowHandlerRegistryUtil.startWorkflowInstance( user.getCompanyId(), page.getGroupId(), userId, - WikiPage.class.getName(), page.getPageId(), page, - serviceContext); + WikiPage.class.getName(), page.getPageId(), page, serviceContext); return page; } @@ -225,8 +224,7 @@ public WikiPage addPage( } public void addPageAttachment( - long userId, long nodeId, String title, String fileName, - File file) + long userId, long nodeId, String title, String fileName, File file) throws PortalException, SystemException { if (Validator.isNull(fileName)) { @@ -418,8 +416,8 @@ public void changeParent( serviceContext.setAssetTagNames(assetTagNames); updatePage( - userId, nodeId, title, version, content, summary, minorEdit, - format, newParentTitle, redirectTitle, serviceContext); + userId, nodeId, title, version, content, summary, minorEdit, format, + newParentTitle, redirectTitle, serviceContext); List oldPages = wikiPagePersistence.findByN_T_H( nodeId, title, false); @@ -837,8 +835,7 @@ public List getPages( throws SystemException { return wikiPagePersistence.findByN_H_S( - nodeId, head, WorkflowConstants.STATUS_APPROVED, start, end, - obc); + nodeId, head, WorkflowConstants.STATUS_APPROVED, start, end, obc); } public List getPages(long nodeId, int start, int end) @@ -1307,8 +1304,7 @@ public WikiPage updatePage( WorkflowHandlerRegistryUtil.startWorkflowInstance( user.getCompanyId(), page.getGroupId(), userId, - WikiPage.class.getName(), page.getPageId(), page, - serviceContext); + WikiPage.class.getName(), page.getPageId(), page, serviceContext); return page; } @@ -1390,8 +1386,8 @@ public WikiPage updateStatus( // Asset Links assetLinkLocalService.updateLinks( - userId, assetEntry.getEntryId(), - assetLinkEntryIds, AssetLinkConstants.TYPE_RELATED); + userId, assetEntry.getEntryId(), assetLinkEntryIds, + AssetLinkConstants.TYPE_RELATED); assetEntryLocalService.deleteEntry( draftAssetEntry.getEntryId()); @@ -1717,8 +1713,7 @@ protected String replaceStyles(String html) { return StringUtil.replace( html, new String[] { - "class=\"diff-html-added\"", - "class=\"diff-html-removed\"", + "class=\"diff-html-added\"", "class=\"diff-html-removed\"", "class=\"diff-html-changed\"", "changeType=\"diff-added-image\"", "changeType=\"diff-removed-image\"", diff --git a/portal-impl/src/com/liferay/portlet/wiki/service/impl/WikiPageServiceImpl.java b/portal-impl/src/com/liferay/portlet/wiki/service/impl/WikiPageServiceImpl.java index 46635b0791ec23..cf3e574a49a041 100644 --- a/portal-impl/src/com/liferay/portlet/wiki/service/impl/WikiPageServiceImpl.java +++ b/portal-impl/src/com/liferay/portlet/wiki/service/impl/WikiPageServiceImpl.java @@ -244,8 +244,8 @@ public String getNodePagesRSS( Locale locale = null; return exportToRSS( - companyId, name, description, type, version, displayStyle, - feedURL, entryURL, pages, diff, locale); + companyId, name, description, type, version, displayStyle, feedURL, + entryURL, pages, diff, locale); } public WikiPage getPage(long nodeId, String title) @@ -472,8 +472,7 @@ else if (displayStyle.equals(RSSUtil.DISPLAY_STYLE_TITLE)) { } protected String getPageDiff( - long companyId, WikiPage latestPage, WikiPage page, - Locale locale) + long companyId, WikiPage latestPage, WikiPage page, Locale locale) throws SystemException { String sourceContent = WikiUtil.processContent(latestPage.getContent()); diff --git a/portal-impl/test/com/liferay/portal/repository/CheckInCheckOutTest.java b/portal-impl/test/com/liferay/portal/repository/CheckInCheckOutTest.java index e6d4e71678dc5d..9d63c516d6c495 100644 --- a/portal-impl/test/com/liferay/portal/repository/CheckInCheckOutTest.java +++ b/portal-impl/test/com/liferay/portal/repository/CheckInCheckOutTest.java @@ -160,9 +160,8 @@ protected FileEntry createFileEntry( _TEST_CONTENT.getBytes()); FileEntry fileEntry = DLAppServiceUtil.addFileEntry( - repositoryId, folderId, fileName, - ContentTypes.TEXT_PLAIN, fileName, null, null, inputStream, - _TEST_CONTENT.length(), serviceContext); + repositoryId, folderId, fileName, ContentTypes.TEXT_PLAIN, fileName, + null, null, inputStream, _TEST_CONTENT.length(), serviceContext); assertNotNull(fileEntry); diff --git a/portal-impl/test/com/liferay/portal/service/http/UserServiceSoapTest.java b/portal-impl/test/com/liferay/portal/service/http/UserServiceSoapTest.java index 1e934a35fc2d25..12e57c0aa1d227 100644 --- a/portal-impl/test/com/liferay/portal/service/http/UserServiceSoapTest.java +++ b/portal-impl/test/com/liferay/portal/service/http/UserServiceSoapTest.java @@ -75,12 +75,11 @@ protected UserSoap addUser() throws Exception { ServiceContext serviceContext = new ServiceContext(); return getUserServiceSoap().addUser( - TestPropsValues.getCompanyId(), autoPassword, - password1, password2, autoScreenName, screenName, emailAddress, - facebookId, openId, locale, firstName, middleName, lastName, - prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear, - jobTitle, groupIds, organizationIds, roleIds, userGroupIds, - sendMail, serviceContext); + TestPropsValues.getCompanyId(), autoPassword, password1, password2, + autoScreenName, screenName, emailAddress, facebookId, openId, + locale, firstName, middleName, lastName, prefixId, suffixId, male, + birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds, + organizationIds, roleIds, userGroupIds, sendMail, serviceContext); } protected UserServiceSoap getUserServiceSoap() throws Exception { diff --git a/portal-impl/test/com/liferay/portal/webdav/WebDAVOSXTest.java b/portal-impl/test/com/liferay/portal/webdav/WebDAVOSXTest.java index 9e96833f3f1042..b765ad380dbcf3 100644 --- a/portal-impl/test/com/liferay/portal/webdav/WebDAVOSXTest.java +++ b/portal-impl/test/com/liferay/portal/webdav/WebDAVOSXTest.java @@ -237,8 +237,7 @@ public void testMSOffice3Modify() throws Exception { HttpServletResponse.SC_CREATED, serviceCopyOrMove(Method.MOVE, _TEST_FILE_NAME, _TEMP_FILE_NAME_2)); assertCode( - HttpServletResponse.SC_NOT_FOUND, - servicePropFind(_TEST_META_NAME)); + HttpServletResponse.SC_NOT_FOUND, servicePropFind(_TEST_META_NAME)); assertCode( HttpServletResponse.SC_NOT_FOUND, servicePropFind(_TEMP_META_NAME_2)); diff --git a/portal-impl/test/com/liferay/portlet/RouterImplTest.java b/portal-impl/test/com/liferay/portlet/RouterImplTest.java index 6df2adda8d4ec3..8cd50ed44cedbb 100644 --- a/portal-impl/test/com/liferay/portlet/RouterImplTest.java +++ b/portal-impl/test/com/liferay/portlet/RouterImplTest.java @@ -102,8 +102,7 @@ public void setUp() throws Exception { public void testGeneratedParameters() { assertUrlGeneratesParameters( - "instance/1b7c/recent", - "p_p_id=15_INSTANCE_1b7c&topLink=recent"); + "instance/1b7c/recent", "p_p_id=15_INSTANCE_1b7c&topLink=recent"); assertUrlRegenerates("instance/1b7c/recent"); } diff --git a/portal-impl/test/com/liferay/portlet/bookmarks/service/BookmarksFolderServiceTest.java b/portal-impl/test/com/liferay/portlet/bookmarks/service/BookmarksFolderServiceTest.java index f08db1d9d9f85d..28ce32733748b1 100644 --- a/portal-impl/test/com/liferay/portlet/bookmarks/service/BookmarksFolderServiceTest.java +++ b/portal-impl/test/com/liferay/portlet/bookmarks/service/BookmarksFolderServiceTest.java @@ -89,8 +89,7 @@ public void testSearch() throws Exception { for (Document doc : results) { assertEquals( - companyId, - GetterUtil.getLong(doc.get(Field.COMPANY_ID))); + companyId, GetterUtil.getLong(doc.get(Field.COMPANY_ID))); assertEquals(groupId, GetterUtil.getLong(doc.get(Field.GROUP_ID))); diff --git a/portal-impl/test/com/liferay/portlet/wiki/engine/creole/TranslationToXHTMLTests.java b/portal-impl/test/com/liferay/portlet/wiki/engine/creole/TranslationToXHTMLTests.java index 06d0339913c336..b0f40867437854 100644 --- a/portal-impl/test/com/liferay/portlet/wiki/engine/creole/TranslationToXHTMLTests.java +++ b/portal-impl/test/com/liferay/portlet/wiki/engine/creole/TranslationToXHTMLTests.java @@ -95,8 +95,7 @@ public void testParseCorrectlyOneItemFirstLevel() { public void testParseCorrectlyOneNonEmptyFirstHeadingBlock() { Assert.assertEquals( - "

Level 1 (largest)

", - translate("heading-1.creole")); + "

Level 1 (largest)

", translate("heading-1.creole")); } public void testParseCorrectlyOneNonEmptyNoWikiBlock() { @@ -107,8 +106,7 @@ public void testParseCorrectlyOneNonEmptyNoWikiBlock() { public void testParseCorrectlyOneNonEmptyNoWikiBlockWitMultipleLines() { Assert.assertEquals( - "
Multiple\nlines
", - translate("nowikiblock-5.creole")); + "
Multiple\nlines
", translate("nowikiblock-5.creole")); } public void testParseCorrectlyOneNonEmptySecondHeadingBlock() { diff --git a/portal-service/src/com/liferay/portal/kernel/atom/AtomEntryContent.java b/portal-service/src/com/liferay/portal/kernel/atom/AtomEntryContent.java index aa9ce565eb0aea..6a894d2225a5f6 100644 --- a/portal-service/src/com/liferay/portal/kernel/atom/AtomEntryContent.java +++ b/portal-service/src/com/liferay/portal/kernel/atom/AtomEntryContent.java @@ -68,11 +68,7 @@ public void setType(Type type) { } public enum Type { - HTML, - MEDIA, - TEXT, - XHTML, - XML + HTML, MEDIA, TEXT, XHTML, XML } private String _mimeType; diff --git a/portal-service/src/com/liferay/portal/kernel/mail/MailMessage.java b/portal-service/src/com/liferay/portal/kernel/mail/MailMessage.java index 0f2cd361cf1c0e..af55a0b0e940a2 100644 --- a/portal-service/src/com/liferay/portal/kernel/mail/MailMessage.java +++ b/portal-service/src/com/liferay/portal/kernel/mail/MailMessage.java @@ -54,8 +54,7 @@ public MailMessage( } public MailMessage( - InternetAddress from, String subject, String body, - boolean htmlFormat) { + InternetAddress from, String subject, String body, boolean htmlFormat) { this(from, null, subject, body, htmlFormat); } diff --git a/portal-service/src/com/liferay/portal/kernel/messaging/InvokerMessageListener.java b/portal-service/src/com/liferay/portal/kernel/messaging/InvokerMessageListener.java index 4c4feca39511d8..264292819f337e 100644 --- a/portal-service/src/com/liferay/portal/kernel/messaging/InvokerMessageListener.java +++ b/portal-service/src/com/liferay/portal/kernel/messaging/InvokerMessageListener.java @@ -20,9 +20,7 @@ public class InvokerMessageListener implements MessageListener { public InvokerMessageListener(MessageListener messageListener) { - this( - messageListener, - Thread.currentThread().getContextClassLoader()); + this(messageListener, Thread.currentThread().getContextClassLoader()); } public InvokerMessageListener( diff --git a/portal-service/src/com/liferay/portal/kernel/process/ProcessExecutor.java b/portal-service/src/com/liferay/portal/kernel/process/ProcessExecutor.java index c443ddb079fe17..f83480288bdee9 100644 --- a/portal-service/src/com/liferay/portal/kernel/process/ProcessExecutor.java +++ b/portal-service/src/com/liferay/portal/kernel/process/ProcessExecutor.java @@ -167,8 +167,7 @@ private static ExecutorService _getExecutorService() { if (_executorService == null) { _executorService = Executors.newCachedThreadPool( new NamedThreadFactory( - ProcessExecutor.class.getName(), - Thread.MIN_PRIORITY, + ProcessExecutor.class.getName(), Thread.MIN_PRIORITY, PortalClassLoaderUtil.getClassLoader())); } } diff --git a/portal-service/src/com/liferay/portal/kernel/repository/BaseRepositoryImpl.java b/portal-service/src/com/liferay/portal/kernel/repository/BaseRepositoryImpl.java index f1113207285b5a..14f364f6ce5ac8 100644 --- a/portal-service/src/com/liferay/portal/kernel/repository/BaseRepositoryImpl.java +++ b/portal-service/src/com/liferay/portal/kernel/repository/BaseRepositoryImpl.java @@ -198,8 +198,7 @@ public Object[] getRepositoryEntryIds(String objectId) } return new Object[] { - repositoryEntry.getRepositoryEntryId(), - repositoryEntry.getUuid() + repositoryEntry.getRepositoryEntryId(), repositoryEntry.getUuid() }; } diff --git a/portal-service/src/com/liferay/portal/kernel/repository/DefaultLocalRepositoryImpl.java b/portal-service/src/com/liferay/portal/kernel/repository/DefaultLocalRepositoryImpl.java index 019eb9386fd7f5..2206f3419e35e2 100644 --- a/portal-service/src/com/liferay/portal/kernel/repository/DefaultLocalRepositoryImpl.java +++ b/portal-service/src/com/liferay/portal/kernel/repository/DefaultLocalRepositoryImpl.java @@ -273,8 +273,8 @@ public FileEntry updateFileEntry( } public Folder updateFolder( - long folderId, long parentFolderId, String title, - String description, ServiceContext serviceContext) { + long folderId, long parentFolderId, String title, String description, + ServiceContext serviceContext) { throw new UnsupportedOperationException(); } diff --git a/portal-service/src/com/liferay/portal/kernel/sanitizer/BaseSanitizer.java b/portal-service/src/com/liferay/portal/kernel/sanitizer/BaseSanitizer.java index 446a4e56823f34..6476e71370a968 100644 --- a/portal-service/src/com/liferay/portal/kernel/sanitizer/BaseSanitizer.java +++ b/portal-service/src/com/liferay/portal/kernel/sanitizer/BaseSanitizer.java @@ -37,9 +37,8 @@ public byte[] sanitize( new ByteArrayOutputStream(); sanitize( - companyId, groupId, userId, className, classPK, contentType, - modes, new ByteArrayInputStream(bytes), byteArrayOutputStream, - options); + companyId, groupId, userId, className, classPK, contentType, modes, + new ByteArrayInputStream(bytes), byteArrayOutputStream, options); return byteArrayOutputStream.toByteArray(); } @@ -61,9 +60,9 @@ public String sanitize( new ByteArrayOutputStream(); sanitize( - companyId, groupId, userId, className, classPK, contentType, - modes, new ByteArrayInputStream(s.getBytes()), - byteArrayOutputStream, options); + companyId, groupId, userId, className, classPK, contentType, modes, + new ByteArrayInputStream(s.getBytes()), byteArrayOutputStream, + options); return byteArrayOutputStream.toString(); } diff --git a/portal-service/src/com/liferay/portal/kernel/search/AbstractSearchEngineConfigurator.java b/portal-service/src/com/liferay/portal/kernel/search/AbstractSearchEngineConfigurator.java index 4330c1d06d63de..69c014f03f9c83 100644 --- a/portal-service/src/com/liferay/portal/kernel/search/AbstractSearchEngineConfigurator.java +++ b/portal-service/src/com/liferay/portal/kernel/search/AbstractSearchEngineConfigurator.java @@ -62,8 +62,7 @@ protected void createSearchEngineListeners( registerSearchEngineMessageListener( searchEngine, searchReaderDestination, - new SearchReaderMessageListener(), - searchEngine.getIndexSearcher()); + new SearchReaderMessageListener(), searchEngine.getIndexSearcher()); registerSearchEngineMessageListener( searchEngine, searchWriterDestination, diff --git a/portal-service/src/com/liferay/portal/kernel/search/BaseIndexer.java b/portal-service/src/com/liferay/portal/kernel/search/BaseIndexer.java index 790b2f0471df6b..c7f85f870f3e63 100644 --- a/portal-service/src/com/liferay/portal/kernel/search/BaseIndexer.java +++ b/portal-service/src/com/liferay/portal/kernel/search/BaseIndexer.java @@ -1,1062 +1,1062 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portal.kernel.search; - -import com.liferay.portal.NoSuchCountryException; -import com.liferay.portal.NoSuchModelException; -import com.liferay.portal.NoSuchRegionException; -import com.liferay.portal.kernel.dao.orm.QueryUtil; -import com.liferay.portal.kernel.exception.PortalException; -import com.liferay.portal.kernel.exception.SystemException; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; -import com.liferay.portal.kernel.search.facet.AssetEntriesFacet; -import com.liferay.portal.kernel.search.facet.Facet; -import com.liferay.portal.kernel.search.facet.MultiValueFacet; -import com.liferay.portal.kernel.search.facet.ScopeFacet; -import com.liferay.portal.kernel.util.GetterUtil; -import com.liferay.portal.kernel.util.ListUtil; -import com.liferay.portal.kernel.util.PropsKeys; -import com.liferay.portal.kernel.util.PropsUtil; -import com.liferay.portal.kernel.util.SetUtil; -import com.liferay.portal.kernel.util.StringUtil; -import com.liferay.portal.kernel.util.Time; -import com.liferay.portal.kernel.util.UnicodeProperties; -import com.liferay.portal.kernel.util.Validator; -import com.liferay.portal.model.Address; -import com.liferay.portal.model.AttachedModel; -import com.liferay.portal.model.AuditedModel; -import com.liferay.portal.model.BaseModel; -import com.liferay.portal.model.Country; -import com.liferay.portal.model.Group; -import com.liferay.portal.model.GroupedModel; -import com.liferay.portal.model.Region; -import com.liferay.portal.model.ResourcedModel; -import com.liferay.portal.model.WorkflowedModel; -import com.liferay.portal.security.permission.ActionKeys; -import com.liferay.portal.security.permission.PermissionChecker; -import com.liferay.portal.security.permission.PermissionThreadLocal; -import com.liferay.portal.service.CountryServiceUtil; -import com.liferay.portal.service.GroupLocalServiceUtil; -import com.liferay.portal.service.RegionServiceUtil; -import com.liferay.portal.util.PortalUtil; -import com.liferay.portlet.asset.model.AssetCategory; -import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil; -import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil; -import com.liferay.portlet.dynamicdatamapping.model.DDMStructure; -import com.liferay.portlet.dynamicdatamapping.util.DDMIndexerUtil; -import com.liferay.portlet.expando.model.ExpandoBridge; -import com.liferay.portlet.expando.model.ExpandoColumnConstants; -import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil; -import com.liferay.portlet.expando.util.ExpandoBridgeIndexerUtil; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import javax.portlet.PortletURL; - -/** - * @author Brian Wing Shun Chan - * @author Hugo Huijser - * @author Ryan Park - * @author Raymond Augé - */ -public abstract class BaseIndexer implements Indexer { - - public static final int INDEX_FILTER_SEARCH_LIMIT = GetterUtil.getInteger( - PropsUtil.get(PropsKeys.INDEX_FILTER_SEARCH_LIMIT)); - - public void delete(long companyId, String uid) throws SearchException { - try { - SearchEngineUtil.deleteDocument(companyId, uid); - } - catch (SearchException se) { - throw se; - } - catch (Exception e) { - throw new SearchException(e); - } - } - - public void delete(Object obj) throws SearchException { - try { - doDelete(obj); - } - catch (SearchException se) { - throw se; - } - catch (Exception e) { - throw new SearchException(e); - } - } - - public Document getDocument(Object obj) throws SearchException { - try { - Document document = doGetDocument(obj); - - for (IndexerPostProcessor indexerPostProcessor : - _indexerPostProcessors) { - - indexerPostProcessor.postProcessDocument(document, obj); - } - - if (document == null) { - return null; - } - - Map fields = document.getFields(); - - Field groupIdField = fields.get(Field.GROUP_ID); - - if (groupIdField != null) { - long groupId = GetterUtil.getLong(groupIdField.getValue()); - - addStagingGroupKeyword(document, groupId); - } - - return document; - } - catch (SearchException se) { - throw se; - } - catch (Exception e) { - throw new SearchException(e); - } - } - - public BooleanQuery getFacetQuery( - String className, SearchContext searchContext) - throws Exception { - - BooleanQuery facetQuery = BooleanQueryFactoryUtil.create(searchContext); - - facetQuery.addExactTerm(Field.ENTRY_CLASS_NAME, className); - - if (searchContext.getUserId() > 0) { - SearchPermissionChecker searchPermissionChecker = - SearchEngineUtil.getSearchPermissionChecker(); - - facetQuery = - (BooleanQuery)searchPermissionChecker.getPermissionQuery( - searchContext.getCompanyId(), searchContext.getGroupIds(), - searchContext.getUserId(), className, facetQuery, - searchContext); - } - - return facetQuery; - } - - public BooleanQuery getFullQuery(SearchContext searchContext) - throws SearchException { - - try { - searchContext.setSearchEngineId(getSearchEngineId()); - - searchContext.setEntryClassNames( - new String[] {getClassName(searchContext)}); - - BooleanQuery contextQuery = BooleanQueryFactoryUtil.create( - searchContext); - - addSearchAssetCategoryIds(contextQuery, searchContext); - addSearchAssetTagNames(contextQuery, searchContext); - addSearchEntryClassNames(contextQuery, searchContext); - addSearchGroupId(contextQuery, searchContext); - - BooleanQuery fullQuery = createFullQuery( - contextQuery, searchContext); - - fullQuery.setQueryConfig(searchContext.getQueryConfig()); - - return fullQuery; - } - catch (SearchException se) { - throw se; - } - catch (Exception e) { - throw new SearchException(e); - } - } - - public IndexerPostProcessor[] getIndexerPostProcessors() { - return _indexerPostProcessors; - } - - public String getSearchEngineId() { - return SearchEngineUtil.SYSTEM_ENGINE_ID; - } - - public String getSortField(String orderByCol) { - String sortField = doGetSortField(orderByCol); - - if (DocumentImpl.isSortableTextField(sortField)) { - return DocumentImpl.getSortableFieldName(sortField); - } - - return sortField; - } - - public Summary getSummary( - Document document, Locale locale, String snippet, - PortletURL portletURL) - throws SearchException { - - try { - Summary summary = doGetSummary( - document, locale, snippet, portletURL); - - for (IndexerPostProcessor indexerPostProcessor : - _indexerPostProcessors) { - - indexerPostProcessor.postProcessSummary( - summary, document, locale, snippet, portletURL); - } - - return summary; - } - catch (SearchException se) { - throw se; - } - catch (Exception e) { - throw new SearchException(e); - } - } - - public boolean hasPermission( - PermissionChecker permissionChecker, long entryClassPK, - String actionId) - throws Exception { - - return true; - } - - public boolean isFilterSearch() { - return _FILTER_SEARCH; - } - - public boolean isIndexerEnabled() { - return _INDEXER_ENABLED; - } - - public boolean isPermissionAware() { - return _PERMISSION_AWARE; - } - - public boolean isStagingAware() { - return _stagingAware; - } - - public void postProcessContextQuery( - BooleanQuery contextQuery, SearchContext searchContext) - throws Exception { - } - - public void postProcessSearchQuery( - BooleanQuery searchQuery, SearchContext searchContext) - throws Exception { - } - - public void registerIndexerPostProcessor( - IndexerPostProcessor indexerPostProcessor) { - - List indexerPostProcessorsList = - ListUtil.fromArray(_indexerPostProcessors); - - indexerPostProcessorsList.add(indexerPostProcessor); - - _indexerPostProcessors = indexerPostProcessorsList.toArray( - new IndexerPostProcessor[indexerPostProcessorsList.size()]); - } - - public void reindex(Object obj) throws SearchException { - try { - if (SearchEngineUtil.isIndexReadOnly() || !isIndexerEnabled()) { - return; - } - - doReindex(obj); - } - catch (SearchException se) { - throw se; - } - catch (Exception e) { - throw new SearchException(e); - } - } - - public void reindex(String className, long classPK) throws SearchException { - try { - if (SearchEngineUtil.isIndexReadOnly() || !isIndexerEnabled()) { - return; - } - - doReindex(className, classPK); - } - catch (NoSuchModelException nsme) { - if (_log.isWarnEnabled()) { - _log.warn("Unable to index " + className + " " + classPK); - } - } - catch (SearchException se) { - throw se; - } - catch (Exception e) { - throw new SearchException(e); - } - } - - public void reindex(String[] ids) throws SearchException { - try { - if (SearchEngineUtil.isIndexReadOnly() || !isIndexerEnabled()) { - return; - } - - doReindex(ids); - } - catch (SearchException se) { - throw se; - } - catch (Exception e) { - throw new SearchException(e); - } - } - - public Hits search(SearchContext searchContext) throws SearchException { - try { - BooleanQuery fullQuery = getFullQuery(searchContext); - - fullQuery.setQueryConfig(searchContext.getQueryConfig()); - - PermissionChecker permissionChecker = - PermissionThreadLocal.getPermissionChecker(); - - int start = searchContext.getStart(); - int end = searchContext.getEnd(); - - if (isFilterSearch() && (permissionChecker != null)) { - searchContext.setStart(0); - searchContext.setEnd(end + INDEX_FILTER_SEARCH_LIMIT); - } - - Hits hits = SearchEngineUtil.search(searchContext, fullQuery); - - searchContext.setStart(start); - searchContext.setEnd(end); - - if (isFilterSearch() && (permissionChecker != null)) { - hits = filterSearch(hits, permissionChecker, searchContext); - } - - return hits; - } - catch (SearchException se) { - throw se; - } - catch (Exception e) { - throw new SearchException(e); - } - } - - public void unregisterIndexerPostProcessor( - IndexerPostProcessor indexerPostProcessor) { - - List indexerPostProcessorsList = - ListUtil.fromArray(_indexerPostProcessors); - - ListUtil.remove(indexerPostProcessorsList, indexerPostProcessor); - - _indexerPostProcessors = indexerPostProcessorsList.toArray( - new IndexerPostProcessor[indexerPostProcessorsList.size()]); - } - - /** - * @deprecated {@link #addSearchLocalizedTerm(BooleanQuery, SearchContext, - * String, boolean)} - */ - protected void addLocalizedSearchTerm( - BooleanQuery searchQuery, SearchContext searchContext, - String field, boolean like) - throws Exception { - - addSearchLocalizedTerm(searchQuery, searchContext, field, like); - } - - protected void addSearchArrayQuery( - BooleanQuery searchQuery, SearchContext searchContext, String field) - throws Exception { - - if (Validator.isNull(field)) { - return; - } - - Object fieldValues = searchContext.getAttribute(field); - - if (fieldValues == null) { - return; - } - - BooleanQuery fieldQuery = null; - - if (fieldValues instanceof int[]) { - int[] fieldValuesArray = (int[])fieldValues; - - if (fieldValuesArray.length == 0) { - return; - } - - fieldQuery = BooleanQueryFactoryUtil.create(searchContext); - - for (int fieldValue : fieldValuesArray) { - fieldQuery.addTerm(field, fieldValue); - } - } - else if (fieldValues instanceof Integer[]) { - Integer[] fieldValuesArray = (Integer[])fieldValues; - - if (fieldValuesArray.length == 0) { - return; - } - - fieldQuery = BooleanQueryFactoryUtil.create(searchContext); - - for (Integer fieldValue : fieldValuesArray) { - fieldQuery.addTerm(field, fieldValue); - } - } - else if (fieldValues instanceof long[]) { - long[] fieldValuesArray = (long[])fieldValues; - - if (fieldValuesArray.length == 0) { - return; - } - - fieldQuery = BooleanQueryFactoryUtil.create(searchContext); - - for (long fieldValue : fieldValuesArray) { - fieldQuery.addTerm(field, fieldValue); - } - } - else if (fieldValues instanceof Long[]) { - Long[] fieldValuesArray = (Long[])fieldValues; - - if (fieldValuesArray.length == 0) { - return; - } - - fieldQuery = BooleanQueryFactoryUtil.create(searchContext); - - for (Long fieldValue : fieldValuesArray) { - fieldQuery.addTerm(field, fieldValue); - } - } - else if (fieldValues instanceof short[]) { - short[] fieldValuesArray = (short[])fieldValues; - - if (fieldValuesArray.length == 0) { - return; - } - - fieldQuery = BooleanQueryFactoryUtil.create(searchContext); - - for (short fieldValue : fieldValuesArray) { - fieldQuery.addTerm(field, fieldValue); - } - } - else if (fieldValues instanceof Short[]) { - Short[] fieldValuesArray = (Short[])fieldValues; - - if (fieldValuesArray.length == 0) { - return; - } - - fieldQuery = BooleanQueryFactoryUtil.create(searchContext); - - for (Short fieldValue : fieldValuesArray) { - fieldQuery.addTerm(field, fieldValue); - } - } - - if (fieldQuery != null) { - if (searchContext.isAndSearch()) { - searchQuery.add(fieldQuery, BooleanClauseOccur.MUST); - } - else { - searchQuery.add(fieldQuery, BooleanClauseOccur.SHOULD); - } - } - } - - protected void addSearchAssetCategoryIds( - BooleanQuery contextQuery, SearchContext searchContext) - throws Exception { - - MultiValueFacet multiValueFacet = new MultiValueFacet(searchContext); - - multiValueFacet.setFieldName(Field.ASSET_CATEGORY_IDS); - multiValueFacet.setStatic(true); - - searchContext.addFacet(multiValueFacet); - } - - protected void addSearchAssetTagNames( - BooleanQuery contextQuery, SearchContext searchContext) - throws Exception { - - MultiValueFacet multiValueFacet = new MultiValueFacet(searchContext); - - multiValueFacet.setFieldName(Field.ASSET_TAG_NAMES); - multiValueFacet.setStatic(true); - - searchContext.addFacet(multiValueFacet); - } - - protected void addSearchDDMStruture( - BooleanQuery searchQuery, SearchContext searchContext, - DDMStructure ddmStructure) - throws Exception { - - Set fieldNames = ddmStructure.getFieldNames(); - - for (String fieldName : fieldNames) { - String name = DDMIndexerUtil.encodeName( - ddmStructure.getStructureId(), fieldName); - - addSearchTerm(searchQuery, searchContext, name, false); - } - } - - protected void addSearchEntryClassNames( - BooleanQuery contextQuery, SearchContext searchContext) - throws Exception { - - Facet facet = new AssetEntriesFacet(searchContext); - - facet.setStatic(true); - - searchContext.addFacet(facet); - } - - protected void addSearchExpando( - BooleanQuery searchQuery, SearchContext searchContext, - String keywords) - throws Exception { - - ExpandoBridge expandoBridge = ExpandoBridgeFactoryUtil.getExpandoBridge( - searchContext.getCompanyId(), getClassName(searchContext)); - - Set attributeNames = SetUtil.fromEnumeration( - expandoBridge.getAttributeNames()); - - for (String attributeName : attributeNames) { - UnicodeProperties properties = expandoBridge.getAttributeProperties( - attributeName); - - int indexType = GetterUtil.getInteger( - properties.getProperty(ExpandoColumnConstants.INDEX_TYPE)); - - if (indexType != ExpandoColumnConstants.INDEX_TYPE_NONE) { - String fieldName = ExpandoBridgeIndexerUtil.encodeFieldName( - attributeName); - - if (Validator.isNotNull(keywords)) { - if (searchContext.isAndSearch()) { - searchQuery.addRequiredTerm(fieldName, keywords); - } - else { - searchQuery.addTerm(fieldName, keywords); - } - } - } - } - } - - protected void addSearchGroupId( - BooleanQuery contextQuery, SearchContext searchContext) - throws Exception { - - Facet facet = new ScopeFacet(searchContext); - - facet.setStatic(true); - - searchContext.addFacet(facet); - } - - protected void addSearchKeywords( - BooleanQuery searchQuery, SearchContext searchContext) - throws Exception { - - String keywords = searchContext.getKeywords(); - - if (Validator.isNull(keywords)) { - return; - } - - searchQuery.addTerms(Field.KEYWORDS, keywords); - - addSearchExpando(searchQuery, searchContext, keywords); - } - - protected void addSearchLocalizedTerm( - BooleanQuery searchQuery, SearchContext searchContext, - String field, boolean like) - throws Exception { - - addSearchTerm(searchQuery, searchContext, field, like); - addSearchTerm( - searchQuery, searchContext, - DocumentImpl.getLocalizedName(searchContext.getLocale(), field), - like); - } - - protected void addSearchTerm( - BooleanQuery searchQuery, SearchContext searchContext, - String field, boolean like) - throws Exception { - - if (Validator.isNull(field)) { - return; - } - - String value = String.valueOf(searchContext.getAttribute(field)); - - if (Validator.isNull(value)) { - value = searchContext.getKeywords(); - } - - if (Validator.isNull(value)) { - return; - } - - if (searchContext.isAndSearch()) { - searchQuery.addRequiredTerm(field, value, like); - } - else { - searchQuery.addTerm(field, value, like); - } - } - - protected void addStagingGroupKeyword(Document document, long groupId) - throws Exception { - - if (!isStagingAware()) { - return; - } - - boolean stagingGroup = false; - - Group group = GroupLocalServiceUtil.getGroup(groupId); - - if (group.isLayout()) { - group = GroupLocalServiceUtil.getGroup(group.getParentGroupId()); - } - - if (group.isStagingGroup()) { - stagingGroup = true; - } - - document.addKeyword(Field.STAGING_GROUP, stagingGroup); - } - - protected BooleanQuery createFullQuery( - BooleanQuery contextQuery, SearchContext searchContext) - throws Exception { - - BooleanQuery searchQuery = BooleanQueryFactoryUtil.create( - searchContext); - - addSearchKeywords(searchQuery, searchContext); - postProcessSearchQuery(searchQuery, searchContext); - - for (IndexerPostProcessor indexerPostProcessor : - _indexerPostProcessors) { - - indexerPostProcessor.postProcessSearchQuery( - searchQuery, searchContext); - } - - Map facets = searchContext.getFacets(); - - for (Facet facet : facets.values()) { - BooleanClause facetClause = facet.getFacetClause(); - - if (facetClause != null) { - contextQuery.add( - facetClause.getQuery(), - facetClause.getBooleanClauseOccur()); - } - } - - BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext); - - fullQuery.add(contextQuery, BooleanClauseOccur.MUST); - - if (searchQuery.hasClauses()) { - fullQuery.add(searchQuery, BooleanClauseOccur.MUST); - } - - BooleanClause[] booleanClauses = searchContext.getBooleanClauses(); - - if (booleanClauses != null) { - for (BooleanClause booleanClause : booleanClauses) { - fullQuery.add( - booleanClause.getQuery(), - booleanClause.getBooleanClauseOccur()); - } - } - - postProcessFullQuery(fullQuery, searchContext); - - for (IndexerPostProcessor indexerPostProcessor : - _indexerPostProcessors) { - - indexerPostProcessor.postProcessFullQuery(fullQuery, searchContext); - } - - return fullQuery; - } - - protected void deleteDocument(long companyId, long field1) - throws Exception { - - deleteDocument(companyId, String.valueOf(field1)); - } - - protected void deleteDocument(long companyId, long field1, String field2) - throws Exception { - - deleteDocument(companyId, String.valueOf(field1), field2); - } - - protected void deleteDocument(long companyId, String field1) - throws Exception { - - Document document = new DocumentImpl(); - - document.addUID(getPortletId(), field1); - - SearchEngineUtil.deleteDocument(companyId, document.get(Field.UID)); - } - - protected void deleteDocument(long companyId, String field1, String field2) - throws Exception { - - Document document = new DocumentImpl(); - - document.addUID(getPortletId(), field1, field2); - - SearchEngineUtil.deleteDocument(companyId, document.get(Field.UID)); - } - - protected abstract void doDelete(Object obj) throws Exception; - - protected abstract Document doGetDocument(Object obj) throws Exception; - - protected String doGetSortField(String orderByCol) { - return orderByCol; - } - - protected abstract Summary doGetSummary( - Document document, Locale locale, String snippet, - PortletURL portletURL) - throws Exception; - - protected abstract void doReindex(Object obj) throws Exception; - - protected abstract void doReindex(String className, long classPK) - throws Exception; - - protected abstract void doReindex(String[] ids) throws Exception; - - protected Hits filterSearch( - Hits hits, PermissionChecker permissionChecker, - SearchContext searchContext) { - - List docs = new ArrayList(); - List scores = new ArrayList(); - - int start = searchContext.getStart(); - int end = searchContext.getEnd(); - - String paginationType = GetterUtil.getString( - searchContext.getAttribute("paginationType"), "more"); - - boolean hasMore = false; - - Document[] documents = hits.getDocs(); - - for (int i = 0; i < documents.length; i++) { - try { - Document document = documents[i]; - - String entryClassName = document.get(Field.ENTRY_CLASS_NAME); - long entryClassPK = GetterUtil.getLong( - document.get(Field.ENTRY_CLASS_PK)); - - Indexer indexer = IndexerRegistryUtil.getIndexer( - entryClassName); - - if ((indexer.isFilterSearch() && indexer.hasPermission( - permissionChecker, entryClassPK, ActionKeys.VIEW)) || - !indexer.isFilterSearch() || - !indexer.isPermissionAware()) { - - docs.add(document); - scores.add(hits.score(i)); - } - } - catch (Exception e) { - } - - if (paginationType.equals("more") && (docs.size() > end)) { - hasMore = true; - - break; - } - } - - int length = docs.size(); - - if (hasMore) { - length = length + (end - start); - } - - hits.setLength(length); - - if ((start != QueryUtil.ALL_POS) && (end != QueryUtil.ALL_POS)) { - if (end > length) { - end = length; - } - - docs = docs.subList(start, end); - } - - hits.setDocs(docs.toArray(new Document[docs.size()])); - hits.setScores(scores.toArray(new Float[docs.size()])); - - hits.setSearchTime( - (float)(System.currentTimeMillis() - hits.getStart()) / - Time.SECOND); - - return hits; - } - - protected Document getBaseModelDocument( - String portletId, BaseModel baseModel) - throws SystemException { - - Document document = new DocumentImpl(); - - String className = baseModel.getModelClassName(); - - long classPK = 0; - long resourcePrimKey = 0; - - if (baseModel instanceof ResourcedModel) { - ResourcedModel resourcedModel = (ResourcedModel)baseModel; - - classPK = resourcedModel.getResourcePrimKey(); - resourcePrimKey = resourcedModel.getResourcePrimKey(); - } - else { - classPK = (Long)baseModel.getPrimaryKeyObj(); - } - - document.addUID(portletId, classPK); - - List assetCategories = - AssetCategoryLocalServiceUtil.getCategories(className, classPK); - - long[] assetCategoryIds = StringUtil.split( - ListUtil.toString( - assetCategories, AssetCategory.CATEGORY_ID_ACCESSOR), - 0L); - - document.addKeyword(Field.ASSET_CATEGORY_IDS, assetCategoryIds); - - String[] assetCategoryNames = StringUtil.split( - ListUtil.toString(assetCategories, AssetCategory.NAME_ACCESSOR)); - - document.addText(Field.ASSET_CATEGORY_NAMES, assetCategoryNames); - - String[] assetTagNames = AssetTagLocalServiceUtil.getTagNames( - className, classPK); - - document.addText(Field.ASSET_TAG_NAMES, assetTagNames); - - document.addKeyword(Field.ENTRY_CLASS_NAME, className); - document.addKeyword(Field.ENTRY_CLASS_PK, classPK); - document.addKeyword(Field.PORTLET_ID, portletId); - - if (resourcePrimKey > 0) { - document.addKeyword(Field.ROOT_ENTRY_CLASS_PK, resourcePrimKey); - } - - if (baseModel instanceof AttachedModel) { - AttachedModel attachedModel = (AttachedModel)baseModel; - - document.addKeyword( - Field.CLASS_NAME_ID, attachedModel.getClassNameId()); - document.addKeyword(Field.CLASS_PK, attachedModel.getClassPK()); - } - - if (baseModel instanceof AuditedModel) { - AuditedModel auditedModel = (AuditedModel)baseModel; - - document.addKeyword(Field.COMPANY_ID, auditedModel.getCompanyId()); - document.addDate(Field.CREATE_DATE, auditedModel.getCreateDate()); - document.addDate( - Field.MODIFIED_DATE, auditedModel.getModifiedDate()); - document.addKeyword(Field.USER_ID, auditedModel.getUserId()); - - String userName = PortalUtil.getUserName( - auditedModel.getUserId(), auditedModel.getUserName()); - - document.addKeyword(Field.USER_NAME, userName, true); - } - - if (baseModel instanceof GroupedModel) { - GroupedModel groupedModel = (GroupedModel)baseModel; - - document.addKeyword( - Field.GROUP_ID, getParentGroupId(groupedModel.getGroupId())); - document.addKeyword( - Field.SCOPE_GROUP_ID, groupedModel.getGroupId()); - } - - if (baseModel instanceof WorkflowedModel) { - WorkflowedModel workflowedModel = (WorkflowedModel)baseModel; - - document.addKeyword(Field.STATUS, workflowedModel.getStatus()); - } - - ExpandoBridgeIndexerUtil.addAttributes( - document, baseModel.getExpandoBridge()); - - return document; - } - - protected String getClassName(SearchContext searchContext) { - String[] classNames = getClassNames(); - - if (classNames.length != 1) { - throw new UnsupportedOperationException( - "Search method needs to be manually implemented for " + - "indexers with more than one class name"); - } - - return classNames[0]; - } - - protected long getParentGroupId(long groupId) { - long parentGroupId = groupId; - - try { - Group group = GroupLocalServiceUtil.getGroup(groupId); - - if (group.isLayout()) { - parentGroupId = group.getParentGroupId(); - } - } - catch (Exception e) { - } - - return parentGroupId; - } - - protected abstract String getPortletId(SearchContext searchContext); - - protected void populateAddresses( - Document document, List
addresses, long regionId, - long countryId) - throws PortalException, SystemException { - - List cities = new ArrayList(); - - List countries = new ArrayList(); - - if (countryId > 0) { - try { - Country country = CountryServiceUtil.getCountry(countryId); - - countries.add(country.getName().toLowerCase()); - } - catch (NoSuchCountryException nsce) { - if (_log.isWarnEnabled()) { - _log.warn(nsce.getMessage()); - } - } - } - - List regions = new ArrayList(); - - if (regionId > 0) { - try { - Region region = RegionServiceUtil.getRegion(regionId); - - regions.add(region.getName().toLowerCase()); - } - catch (NoSuchRegionException nsre) { - if (_log.isWarnEnabled()) { - _log.warn(nsre.getMessage()); - } - } - } - - List streets = new ArrayList(); - List zips = new ArrayList(); - - for (Address address : addresses) { - cities.add(address.getCity().toLowerCase()); - countries.add(address.getCountry().getName().toLowerCase()); - regions.add(address.getRegion().getName().toLowerCase()); - streets.add(address.getStreet1().toLowerCase()); - streets.add(address.getStreet2().toLowerCase()); - streets.add(address.getStreet3().toLowerCase()); - zips.add(address.getZip().toLowerCase()); - } - - document.addText("city", cities.toArray(new String[cities.size()])); - document.addText( - "country", countries.toArray(new String[countries.size()])); - document.addText("region", regions.toArray(new String[regions.size()])); - document.addText("street", streets.toArray(new String[streets.size()])); - document.addText("zip", zips.toArray(new String[zips.size()])); - } - - protected void postProcessFullQuery( - BooleanQuery fullQuery, SearchContext searchContext) - throws Exception { - } - - protected void setStagingAware(boolean stagingAware) { - _stagingAware = stagingAware; - } - - private static final boolean _FILTER_SEARCH = false; - - private static final boolean _INDEXER_ENABLED = true; - - private static final boolean _PERMISSION_AWARE = false; - - private static Log _log = LogFactoryUtil.getLog(BaseIndexer.class); - - private IndexerPostProcessor[] _indexerPostProcessors = - new IndexerPostProcessor[0]; - private boolean _stagingAware = true; - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portal.kernel.search; + +import com.liferay.portal.NoSuchCountryException; +import com.liferay.portal.NoSuchModelException; +import com.liferay.portal.NoSuchRegionException; +import com.liferay.portal.kernel.dao.orm.QueryUtil; +import com.liferay.portal.kernel.exception.PortalException; +import com.liferay.portal.kernel.exception.SystemException; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; +import com.liferay.portal.kernel.search.facet.AssetEntriesFacet; +import com.liferay.portal.kernel.search.facet.Facet; +import com.liferay.portal.kernel.search.facet.MultiValueFacet; +import com.liferay.portal.kernel.search.facet.ScopeFacet; +import com.liferay.portal.kernel.util.GetterUtil; +import com.liferay.portal.kernel.util.ListUtil; +import com.liferay.portal.kernel.util.PropsKeys; +import com.liferay.portal.kernel.util.PropsUtil; +import com.liferay.portal.kernel.util.SetUtil; +import com.liferay.portal.kernel.util.StringUtil; +import com.liferay.portal.kernel.util.Time; +import com.liferay.portal.kernel.util.UnicodeProperties; +import com.liferay.portal.kernel.util.Validator; +import com.liferay.portal.model.Address; +import com.liferay.portal.model.AttachedModel; +import com.liferay.portal.model.AuditedModel; +import com.liferay.portal.model.BaseModel; +import com.liferay.portal.model.Country; +import com.liferay.portal.model.Group; +import com.liferay.portal.model.GroupedModel; +import com.liferay.portal.model.Region; +import com.liferay.portal.model.ResourcedModel; +import com.liferay.portal.model.WorkflowedModel; +import com.liferay.portal.security.permission.ActionKeys; +import com.liferay.portal.security.permission.PermissionChecker; +import com.liferay.portal.security.permission.PermissionThreadLocal; +import com.liferay.portal.service.CountryServiceUtil; +import com.liferay.portal.service.GroupLocalServiceUtil; +import com.liferay.portal.service.RegionServiceUtil; +import com.liferay.portal.util.PortalUtil; +import com.liferay.portlet.asset.model.AssetCategory; +import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil; +import com.liferay.portlet.asset.service.AssetTagLocalServiceUtil; +import com.liferay.portlet.dynamicdatamapping.model.DDMStructure; +import com.liferay.portlet.dynamicdatamapping.util.DDMIndexerUtil; +import com.liferay.portlet.expando.model.ExpandoBridge; +import com.liferay.portlet.expando.model.ExpandoColumnConstants; +import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil; +import com.liferay.portlet.expando.util.ExpandoBridgeIndexerUtil; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; + +import javax.portlet.PortletURL; + +/** + * @author Brian Wing Shun Chan + * @author Hugo Huijser + * @author Ryan Park + * @author Raymond Augé + */ +public abstract class BaseIndexer implements Indexer { + + public static final int INDEX_FILTER_SEARCH_LIMIT = GetterUtil.getInteger( + PropsUtil.get(PropsKeys.INDEX_FILTER_SEARCH_LIMIT)); + + public void delete(long companyId, String uid) throws SearchException { + try { + SearchEngineUtil.deleteDocument(companyId, uid); + } + catch (SearchException se) { + throw se; + } + catch (Exception e) { + throw new SearchException(e); + } + } + + public void delete(Object obj) throws SearchException { + try { + doDelete(obj); + } + catch (SearchException se) { + throw se; + } + catch (Exception e) { + throw new SearchException(e); + } + } + + public Document getDocument(Object obj) throws SearchException { + try { + Document document = doGetDocument(obj); + + for (IndexerPostProcessor indexerPostProcessor : + _indexerPostProcessors) { + + indexerPostProcessor.postProcessDocument(document, obj); + } + + if (document == null) { + return null; + } + + Map fields = document.getFields(); + + Field groupIdField = fields.get(Field.GROUP_ID); + + if (groupIdField != null) { + long groupId = GetterUtil.getLong(groupIdField.getValue()); + + addStagingGroupKeyword(document, groupId); + } + + return document; + } + catch (SearchException se) { + throw se; + } + catch (Exception e) { + throw new SearchException(e); + } + } + + public BooleanQuery getFacetQuery( + String className, SearchContext searchContext) + throws Exception { + + BooleanQuery facetQuery = BooleanQueryFactoryUtil.create(searchContext); + + facetQuery.addExactTerm(Field.ENTRY_CLASS_NAME, className); + + if (searchContext.getUserId() > 0) { + SearchPermissionChecker searchPermissionChecker = + SearchEngineUtil.getSearchPermissionChecker(); + + facetQuery = + (BooleanQuery)searchPermissionChecker.getPermissionQuery( + searchContext.getCompanyId(), searchContext.getGroupIds(), + searchContext.getUserId(), className, facetQuery, + searchContext); + } + + return facetQuery; + } + + public BooleanQuery getFullQuery(SearchContext searchContext) + throws SearchException { + + try { + searchContext.setSearchEngineId(getSearchEngineId()); + + searchContext.setEntryClassNames( + new String[] {getClassName(searchContext)}); + + BooleanQuery contextQuery = BooleanQueryFactoryUtil.create( + searchContext); + + addSearchAssetCategoryIds(contextQuery, searchContext); + addSearchAssetTagNames(contextQuery, searchContext); + addSearchEntryClassNames(contextQuery, searchContext); + addSearchGroupId(contextQuery, searchContext); + + BooleanQuery fullQuery = createFullQuery( + contextQuery, searchContext); + + fullQuery.setQueryConfig(searchContext.getQueryConfig()); + + return fullQuery; + } + catch (SearchException se) { + throw se; + } + catch (Exception e) { + throw new SearchException(e); + } + } + + public IndexerPostProcessor[] getIndexerPostProcessors() { + return _indexerPostProcessors; + } + + public String getSearchEngineId() { + return SearchEngineUtil.SYSTEM_ENGINE_ID; + } + + public String getSortField(String orderByCol) { + String sortField = doGetSortField(orderByCol); + + if (DocumentImpl.isSortableTextField(sortField)) { + return DocumentImpl.getSortableFieldName(sortField); + } + + return sortField; + } + + public Summary getSummary( + Document document, Locale locale, String snippet, + PortletURL portletURL) + throws SearchException { + + try { + Summary summary = doGetSummary( + document, locale, snippet, portletURL); + + for (IndexerPostProcessor indexerPostProcessor : + _indexerPostProcessors) { + + indexerPostProcessor.postProcessSummary( + summary, document, locale, snippet, portletURL); + } + + return summary; + } + catch (SearchException se) { + throw se; + } + catch (Exception e) { + throw new SearchException(e); + } + } + + public boolean hasPermission( + PermissionChecker permissionChecker, long entryClassPK, + String actionId) + throws Exception { + + return true; + } + + public boolean isFilterSearch() { + return _FILTER_SEARCH; + } + + public boolean isIndexerEnabled() { + return _INDEXER_ENABLED; + } + + public boolean isPermissionAware() { + return _PERMISSION_AWARE; + } + + public boolean isStagingAware() { + return _stagingAware; + } + + public void postProcessContextQuery( + BooleanQuery contextQuery, SearchContext searchContext) + throws Exception { + } + + public void postProcessSearchQuery( + BooleanQuery searchQuery, SearchContext searchContext) + throws Exception { + } + + public void registerIndexerPostProcessor( + IndexerPostProcessor indexerPostProcessor) { + + List indexerPostProcessorsList = + ListUtil.fromArray(_indexerPostProcessors); + + indexerPostProcessorsList.add(indexerPostProcessor); + + _indexerPostProcessors = indexerPostProcessorsList.toArray( + new IndexerPostProcessor[indexerPostProcessorsList.size()]); + } + + public void reindex(Object obj) throws SearchException { + try { + if (SearchEngineUtil.isIndexReadOnly() || !isIndexerEnabled()) { + return; + } + + doReindex(obj); + } + catch (SearchException se) { + throw se; + } + catch (Exception e) { + throw new SearchException(e); + } + } + + public void reindex(String className, long classPK) throws SearchException { + try { + if (SearchEngineUtil.isIndexReadOnly() || !isIndexerEnabled()) { + return; + } + + doReindex(className, classPK); + } + catch (NoSuchModelException nsme) { + if (_log.isWarnEnabled()) { + _log.warn("Unable to index " + className + " " + classPK); + } + } + catch (SearchException se) { + throw se; + } + catch (Exception e) { + throw new SearchException(e); + } + } + + public void reindex(String[] ids) throws SearchException { + try { + if (SearchEngineUtil.isIndexReadOnly() || !isIndexerEnabled()) { + return; + } + + doReindex(ids); + } + catch (SearchException se) { + throw se; + } + catch (Exception e) { + throw new SearchException(e); + } + } + + public Hits search(SearchContext searchContext) throws SearchException { + try { + BooleanQuery fullQuery = getFullQuery(searchContext); + + fullQuery.setQueryConfig(searchContext.getQueryConfig()); + + PermissionChecker permissionChecker = + PermissionThreadLocal.getPermissionChecker(); + + int start = searchContext.getStart(); + int end = searchContext.getEnd(); + + if (isFilterSearch() && (permissionChecker != null)) { + searchContext.setStart(0); + searchContext.setEnd(end + INDEX_FILTER_SEARCH_LIMIT); + } + + Hits hits = SearchEngineUtil.search(searchContext, fullQuery); + + searchContext.setStart(start); + searchContext.setEnd(end); + + if (isFilterSearch() && (permissionChecker != null)) { + hits = filterSearch(hits, permissionChecker, searchContext); + } + + return hits; + } + catch (SearchException se) { + throw se; + } + catch (Exception e) { + throw new SearchException(e); + } + } + + public void unregisterIndexerPostProcessor( + IndexerPostProcessor indexerPostProcessor) { + + List indexerPostProcessorsList = + ListUtil.fromArray(_indexerPostProcessors); + + ListUtil.remove(indexerPostProcessorsList, indexerPostProcessor); + + _indexerPostProcessors = indexerPostProcessorsList.toArray( + new IndexerPostProcessor[indexerPostProcessorsList.size()]); + } + + /** + * @deprecated {@link #addSearchLocalizedTerm(BooleanQuery, SearchContext, + * String, boolean)} + */ + protected void addLocalizedSearchTerm( + BooleanQuery searchQuery, SearchContext searchContext, String field, + boolean like) + throws Exception { + + addSearchLocalizedTerm(searchQuery, searchContext, field, like); + } + + protected void addSearchArrayQuery( + BooleanQuery searchQuery, SearchContext searchContext, String field) + throws Exception { + + if (Validator.isNull(field)) { + return; + } + + Object fieldValues = searchContext.getAttribute(field); + + if (fieldValues == null) { + return; + } + + BooleanQuery fieldQuery = null; + + if (fieldValues instanceof int[]) { + int[] fieldValuesArray = (int[])fieldValues; + + if (fieldValuesArray.length == 0) { + return; + } + + fieldQuery = BooleanQueryFactoryUtil.create(searchContext); + + for (int fieldValue : fieldValuesArray) { + fieldQuery.addTerm(field, fieldValue); + } + } + else if (fieldValues instanceof Integer[]) { + Integer[] fieldValuesArray = (Integer[])fieldValues; + + if (fieldValuesArray.length == 0) { + return; + } + + fieldQuery = BooleanQueryFactoryUtil.create(searchContext); + + for (Integer fieldValue : fieldValuesArray) { + fieldQuery.addTerm(field, fieldValue); + } + } + else if (fieldValues instanceof long[]) { + long[] fieldValuesArray = (long[])fieldValues; + + if (fieldValuesArray.length == 0) { + return; + } + + fieldQuery = BooleanQueryFactoryUtil.create(searchContext); + + for (long fieldValue : fieldValuesArray) { + fieldQuery.addTerm(field, fieldValue); + } + } + else if (fieldValues instanceof Long[]) { + Long[] fieldValuesArray = (Long[])fieldValues; + + if (fieldValuesArray.length == 0) { + return; + } + + fieldQuery = BooleanQueryFactoryUtil.create(searchContext); + + for (Long fieldValue : fieldValuesArray) { + fieldQuery.addTerm(field, fieldValue); + } + } + else if (fieldValues instanceof short[]) { + short[] fieldValuesArray = (short[])fieldValues; + + if (fieldValuesArray.length == 0) { + return; + } + + fieldQuery = BooleanQueryFactoryUtil.create(searchContext); + + for (short fieldValue : fieldValuesArray) { + fieldQuery.addTerm(field, fieldValue); + } + } + else if (fieldValues instanceof Short[]) { + Short[] fieldValuesArray = (Short[])fieldValues; + + if (fieldValuesArray.length == 0) { + return; + } + + fieldQuery = BooleanQueryFactoryUtil.create(searchContext); + + for (Short fieldValue : fieldValuesArray) { + fieldQuery.addTerm(field, fieldValue); + } + } + + if (fieldQuery != null) { + if (searchContext.isAndSearch()) { + searchQuery.add(fieldQuery, BooleanClauseOccur.MUST); + } + else { + searchQuery.add(fieldQuery, BooleanClauseOccur.SHOULD); + } + } + } + + protected void addSearchAssetCategoryIds( + BooleanQuery contextQuery, SearchContext searchContext) + throws Exception { + + MultiValueFacet multiValueFacet = new MultiValueFacet(searchContext); + + multiValueFacet.setFieldName(Field.ASSET_CATEGORY_IDS); + multiValueFacet.setStatic(true); + + searchContext.addFacet(multiValueFacet); + } + + protected void addSearchAssetTagNames( + BooleanQuery contextQuery, SearchContext searchContext) + throws Exception { + + MultiValueFacet multiValueFacet = new MultiValueFacet(searchContext); + + multiValueFacet.setFieldName(Field.ASSET_TAG_NAMES); + multiValueFacet.setStatic(true); + + searchContext.addFacet(multiValueFacet); + } + + protected void addSearchDDMStruture( + BooleanQuery searchQuery, SearchContext searchContext, + DDMStructure ddmStructure) + throws Exception { + + Set fieldNames = ddmStructure.getFieldNames(); + + for (String fieldName : fieldNames) { + String name = DDMIndexerUtil.encodeName( + ddmStructure.getStructureId(), fieldName); + + addSearchTerm(searchQuery, searchContext, name, false); + } + } + + protected void addSearchEntryClassNames( + BooleanQuery contextQuery, SearchContext searchContext) + throws Exception { + + Facet facet = new AssetEntriesFacet(searchContext); + + facet.setStatic(true); + + searchContext.addFacet(facet); + } + + protected void addSearchExpando( + BooleanQuery searchQuery, SearchContext searchContext, + String keywords) + throws Exception { + + ExpandoBridge expandoBridge = ExpandoBridgeFactoryUtil.getExpandoBridge( + searchContext.getCompanyId(), getClassName(searchContext)); + + Set attributeNames = SetUtil.fromEnumeration( + expandoBridge.getAttributeNames()); + + for (String attributeName : attributeNames) { + UnicodeProperties properties = expandoBridge.getAttributeProperties( + attributeName); + + int indexType = GetterUtil.getInteger( + properties.getProperty(ExpandoColumnConstants.INDEX_TYPE)); + + if (indexType != ExpandoColumnConstants.INDEX_TYPE_NONE) { + String fieldName = ExpandoBridgeIndexerUtil.encodeFieldName( + attributeName); + + if (Validator.isNotNull(keywords)) { + if (searchContext.isAndSearch()) { + searchQuery.addRequiredTerm(fieldName, keywords); + } + else { + searchQuery.addTerm(fieldName, keywords); + } + } + } + } + } + + protected void addSearchGroupId( + BooleanQuery contextQuery, SearchContext searchContext) + throws Exception { + + Facet facet = new ScopeFacet(searchContext); + + facet.setStatic(true); + + searchContext.addFacet(facet); + } + + protected void addSearchKeywords( + BooleanQuery searchQuery, SearchContext searchContext) + throws Exception { + + String keywords = searchContext.getKeywords(); + + if (Validator.isNull(keywords)) { + return; + } + + searchQuery.addTerms(Field.KEYWORDS, keywords); + + addSearchExpando(searchQuery, searchContext, keywords); + } + + protected void addSearchLocalizedTerm( + BooleanQuery searchQuery, SearchContext searchContext, String field, + boolean like) + throws Exception { + + addSearchTerm(searchQuery, searchContext, field, like); + addSearchTerm( + searchQuery, searchContext, + DocumentImpl.getLocalizedName(searchContext.getLocale(), field), + like); + } + + protected void addSearchTerm( + BooleanQuery searchQuery, SearchContext searchContext, String field, + boolean like) + throws Exception { + + if (Validator.isNull(field)) { + return; + } + + String value = String.valueOf(searchContext.getAttribute(field)); + + if (Validator.isNull(value)) { + value = searchContext.getKeywords(); + } + + if (Validator.isNull(value)) { + return; + } + + if (searchContext.isAndSearch()) { + searchQuery.addRequiredTerm(field, value, like); + } + else { + searchQuery.addTerm(field, value, like); + } + } + + protected void addStagingGroupKeyword(Document document, long groupId) + throws Exception { + + if (!isStagingAware()) { + return; + } + + boolean stagingGroup = false; + + Group group = GroupLocalServiceUtil.getGroup(groupId); + + if (group.isLayout()) { + group = GroupLocalServiceUtil.getGroup(group.getParentGroupId()); + } + + if (group.isStagingGroup()) { + stagingGroup = true; + } + + document.addKeyword(Field.STAGING_GROUP, stagingGroup); + } + + protected BooleanQuery createFullQuery( + BooleanQuery contextQuery, SearchContext searchContext) + throws Exception { + + BooleanQuery searchQuery = BooleanQueryFactoryUtil.create( + searchContext); + + addSearchKeywords(searchQuery, searchContext); + postProcessSearchQuery(searchQuery, searchContext); + + for (IndexerPostProcessor indexerPostProcessor : + _indexerPostProcessors) { + + indexerPostProcessor.postProcessSearchQuery( + searchQuery, searchContext); + } + + Map facets = searchContext.getFacets(); + + for (Facet facet : facets.values()) { + BooleanClause facetClause = facet.getFacetClause(); + + if (facetClause != null) { + contextQuery.add( + facetClause.getQuery(), + facetClause.getBooleanClauseOccur()); + } + } + + BooleanQuery fullQuery = BooleanQueryFactoryUtil.create(searchContext); + + fullQuery.add(contextQuery, BooleanClauseOccur.MUST); + + if (searchQuery.hasClauses()) { + fullQuery.add(searchQuery, BooleanClauseOccur.MUST); + } + + BooleanClause[] booleanClauses = searchContext.getBooleanClauses(); + + if (booleanClauses != null) { + for (BooleanClause booleanClause : booleanClauses) { + fullQuery.add( + booleanClause.getQuery(), + booleanClause.getBooleanClauseOccur()); + } + } + + postProcessFullQuery(fullQuery, searchContext); + + for (IndexerPostProcessor indexerPostProcessor : + _indexerPostProcessors) { + + indexerPostProcessor.postProcessFullQuery(fullQuery, searchContext); + } + + return fullQuery; + } + + protected void deleteDocument(long companyId, long field1) + throws Exception { + + deleteDocument(companyId, String.valueOf(field1)); + } + + protected void deleteDocument(long companyId, long field1, String field2) + throws Exception { + + deleteDocument(companyId, String.valueOf(field1), field2); + } + + protected void deleteDocument(long companyId, String field1) + throws Exception { + + Document document = new DocumentImpl(); + + document.addUID(getPortletId(), field1); + + SearchEngineUtil.deleteDocument(companyId, document.get(Field.UID)); + } + + protected void deleteDocument(long companyId, String field1, String field2) + throws Exception { + + Document document = new DocumentImpl(); + + document.addUID(getPortletId(), field1, field2); + + SearchEngineUtil.deleteDocument(companyId, document.get(Field.UID)); + } + + protected abstract void doDelete(Object obj) throws Exception; + + protected abstract Document doGetDocument(Object obj) throws Exception; + + protected String doGetSortField(String orderByCol) { + return orderByCol; + } + + protected abstract Summary doGetSummary( + Document document, Locale locale, String snippet, + PortletURL portletURL) + throws Exception; + + protected abstract void doReindex(Object obj) throws Exception; + + protected abstract void doReindex(String className, long classPK) + throws Exception; + + protected abstract void doReindex(String[] ids) throws Exception; + + protected Hits filterSearch( + Hits hits, PermissionChecker permissionChecker, + SearchContext searchContext) { + + List docs = new ArrayList(); + List scores = new ArrayList(); + + int start = searchContext.getStart(); + int end = searchContext.getEnd(); + + String paginationType = GetterUtil.getString( + searchContext.getAttribute("paginationType"), "more"); + + boolean hasMore = false; + + Document[] documents = hits.getDocs(); + + for (int i = 0; i < documents.length; i++) { + try { + Document document = documents[i]; + + String entryClassName = document.get(Field.ENTRY_CLASS_NAME); + long entryClassPK = GetterUtil.getLong( + document.get(Field.ENTRY_CLASS_PK)); + + Indexer indexer = IndexerRegistryUtil.getIndexer( + entryClassName); + + if ((indexer.isFilterSearch() && indexer.hasPermission( + permissionChecker, entryClassPK, ActionKeys.VIEW)) || + !indexer.isFilterSearch() || + !indexer.isPermissionAware()) { + + docs.add(document); + scores.add(hits.score(i)); + } + } + catch (Exception e) { + } + + if (paginationType.equals("more") && (docs.size() > end)) { + hasMore = true; + + break; + } + } + + int length = docs.size(); + + if (hasMore) { + length = length + (end - start); + } + + hits.setLength(length); + + if ((start != QueryUtil.ALL_POS) && (end != QueryUtil.ALL_POS)) { + if (end > length) { + end = length; + } + + docs = docs.subList(start, end); + } + + hits.setDocs(docs.toArray(new Document[docs.size()])); + hits.setScores(scores.toArray(new Float[docs.size()])); + + hits.setSearchTime( + (float)(System.currentTimeMillis() - hits.getStart()) / + Time.SECOND); + + return hits; + } + + protected Document getBaseModelDocument( + String portletId, BaseModel baseModel) + throws SystemException { + + Document document = new DocumentImpl(); + + String className = baseModel.getModelClassName(); + + long classPK = 0; + long resourcePrimKey = 0; + + if (baseModel instanceof ResourcedModel) { + ResourcedModel resourcedModel = (ResourcedModel)baseModel; + + classPK = resourcedModel.getResourcePrimKey(); + resourcePrimKey = resourcedModel.getResourcePrimKey(); + } + else { + classPK = (Long)baseModel.getPrimaryKeyObj(); + } + + document.addUID(portletId, classPK); + + List assetCategories = + AssetCategoryLocalServiceUtil.getCategories(className, classPK); + + long[] assetCategoryIds = StringUtil.split( + ListUtil.toString( + assetCategories, AssetCategory.CATEGORY_ID_ACCESSOR), + 0L); + + document.addKeyword(Field.ASSET_CATEGORY_IDS, assetCategoryIds); + + String[] assetCategoryNames = StringUtil.split( + ListUtil.toString(assetCategories, AssetCategory.NAME_ACCESSOR)); + + document.addText(Field.ASSET_CATEGORY_NAMES, assetCategoryNames); + + String[] assetTagNames = AssetTagLocalServiceUtil.getTagNames( + className, classPK); + + document.addText(Field.ASSET_TAG_NAMES, assetTagNames); + + document.addKeyword(Field.ENTRY_CLASS_NAME, className); + document.addKeyword(Field.ENTRY_CLASS_PK, classPK); + document.addKeyword(Field.PORTLET_ID, portletId); + + if (resourcePrimKey > 0) { + document.addKeyword(Field.ROOT_ENTRY_CLASS_PK, resourcePrimKey); + } + + if (baseModel instanceof AttachedModel) { + AttachedModel attachedModel = (AttachedModel)baseModel; + + document.addKeyword( + Field.CLASS_NAME_ID, attachedModel.getClassNameId()); + document.addKeyword(Field.CLASS_PK, attachedModel.getClassPK()); + } + + if (baseModel instanceof AuditedModel) { + AuditedModel auditedModel = (AuditedModel)baseModel; + + document.addKeyword(Field.COMPANY_ID, auditedModel.getCompanyId()); + document.addDate(Field.CREATE_DATE, auditedModel.getCreateDate()); + document.addDate( + Field.MODIFIED_DATE, auditedModel.getModifiedDate()); + document.addKeyword(Field.USER_ID, auditedModel.getUserId()); + + String userName = PortalUtil.getUserName( + auditedModel.getUserId(), auditedModel.getUserName()); + + document.addKeyword(Field.USER_NAME, userName, true); + } + + if (baseModel instanceof GroupedModel) { + GroupedModel groupedModel = (GroupedModel)baseModel; + + document.addKeyword( + Field.GROUP_ID, getParentGroupId(groupedModel.getGroupId())); + document.addKeyword( + Field.SCOPE_GROUP_ID, groupedModel.getGroupId()); + } + + if (baseModel instanceof WorkflowedModel) { + WorkflowedModel workflowedModel = (WorkflowedModel)baseModel; + + document.addKeyword(Field.STATUS, workflowedModel.getStatus()); + } + + ExpandoBridgeIndexerUtil.addAttributes( + document, baseModel.getExpandoBridge()); + + return document; + } + + protected String getClassName(SearchContext searchContext) { + String[] classNames = getClassNames(); + + if (classNames.length != 1) { + throw new UnsupportedOperationException( + "Search method needs to be manually implemented for " + + "indexers with more than one class name"); + } + + return classNames[0]; + } + + protected long getParentGroupId(long groupId) { + long parentGroupId = groupId; + + try { + Group group = GroupLocalServiceUtil.getGroup(groupId); + + if (group.isLayout()) { + parentGroupId = group.getParentGroupId(); + } + } + catch (Exception e) { + } + + return parentGroupId; + } + + protected abstract String getPortletId(SearchContext searchContext); + + protected void populateAddresses( + Document document, List
addresses, long regionId, + long countryId) + throws PortalException, SystemException { + + List cities = new ArrayList(); + + List countries = new ArrayList(); + + if (countryId > 0) { + try { + Country country = CountryServiceUtil.getCountry(countryId); + + countries.add(country.getName().toLowerCase()); + } + catch (NoSuchCountryException nsce) { + if (_log.isWarnEnabled()) { + _log.warn(nsce.getMessage()); + } + } + } + + List regions = new ArrayList(); + + if (regionId > 0) { + try { + Region region = RegionServiceUtil.getRegion(regionId); + + regions.add(region.getName().toLowerCase()); + } + catch (NoSuchRegionException nsre) { + if (_log.isWarnEnabled()) { + _log.warn(nsre.getMessage()); + } + } + } + + List streets = new ArrayList(); + List zips = new ArrayList(); + + for (Address address : addresses) { + cities.add(address.getCity().toLowerCase()); + countries.add(address.getCountry().getName().toLowerCase()); + regions.add(address.getRegion().getName().toLowerCase()); + streets.add(address.getStreet1().toLowerCase()); + streets.add(address.getStreet2().toLowerCase()); + streets.add(address.getStreet3().toLowerCase()); + zips.add(address.getZip().toLowerCase()); + } + + document.addText("city", cities.toArray(new String[cities.size()])); + document.addText( + "country", countries.toArray(new String[countries.size()])); + document.addText("region", regions.toArray(new String[regions.size()])); + document.addText("street", streets.toArray(new String[streets.size()])); + document.addText("zip", zips.toArray(new String[zips.size()])); + } + + protected void postProcessFullQuery( + BooleanQuery fullQuery, SearchContext searchContext) + throws Exception { + } + + protected void setStagingAware(boolean stagingAware) { + _stagingAware = stagingAware; + } + + private static final boolean _FILTER_SEARCH = false; + + private static final boolean _INDEXER_ENABLED = true; + + private static final boolean _PERMISSION_AWARE = false; + + private static Log _log = LogFactoryUtil.getLog(BaseIndexer.class); + + private IndexerPostProcessor[] _indexerPostProcessors = + new IndexerPostProcessor[0]; + private boolean _stagingAware = true; + } \ No newline at end of file diff --git a/portal-service/src/com/liferay/portal/kernel/search/facet/ModifiedFacet.java b/portal-service/src/com/liferay/portal/kernel/search/facet/ModifiedFacet.java index 3c0e3d57a5a776..a6938df91ea253 100644 --- a/portal-service/src/com/liferay/portal/kernel/search/facet/ModifiedFacet.java +++ b/portal-service/src/com/liferay/portal/kernel/search/facet/ModifiedFacet.java @@ -91,12 +91,8 @@ protected void normalizeDates( rangeString = StringUtil.replace( rangeString, new String[] { - "past-hour", - "past-24-hours", - "past-week", - "past-month", - "past-year", - "*" + "past-hour", "past-24-hours", "past-week", "past-month", + "past-year", "*" }, new String[] { dateFormat.format(pastHour.getTime()), diff --git a/portal-service/src/com/liferay/portal/kernel/util/Base64.java b/portal-service/src/com/liferay/portal/kernel/util/Base64.java index 637cf18e01dabc..aa422268285a8c 100644 --- a/portal-service/src/com/liferay/portal/kernel/util/Base64.java +++ b/portal-service/src/com/liferay/portal/kernel/util/Base64.java @@ -1,259 +1,251 @@ -/** - * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. - * - * This library is free software; you can redistribute it and/or modify it under - * the terms of the GNU Lesser General Public License as published by the Free - * Software Foundation; either version 2.1 of the License, or (at your option) - * any later version. - * - * This library is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more - * details. - */ - -package com.liferay.portal.kernel.util; - -import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream; -import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream; -import com.liferay.portal.kernel.log.Log; -import com.liferay.portal.kernel.log.LogFactoryUtil; - -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; - -/** - * @author Brian Wing Shun Chan - */ -public class Base64 { - - public static byte[] decode(String base64) { - if (Validator.isNull(base64)) { - return new byte[0]; - } - - int pad = 0; - - for (int i = base64.length() - 1; base64.charAt(i) == CharPool.EQUAL; - i--) { - - pad++; - } - - int length = (base64.length() * 6) / 8 - pad; - byte raw[] = new byte[length]; - int rawindex = 0; - - for (int i = 0; i < base64.length(); i += 4) { - int block = (getValue(base64.charAt(i)) << 18) + - (getValue(base64.charAt(i + 1)) << 12) + - (getValue(base64.charAt(i + 2)) << 6) + - getValue(base64.charAt(i + 3)); - - for (int j = 0; j < 3 && rawindex + j < raw.length; j++) { - raw[rawindex + j] = (byte)(block >> 8 * (2 - j) & 0xff); - } - - rawindex += 3; - } - - return raw; - } - - public static String encode(byte raw[]) { - return encode(raw, 0, raw.length); - } - - public static String encode(byte raw[], int offset, int length) { - int lastIndex = Math.min(raw.length, offset + length); - - StringBuilder sb = new StringBuilder( - ((lastIndex - offset) / 3 + 1) * 4); - - for (int i = offset; i < lastIndex; i += 3) { - sb.append(encodeBlock(raw, i, lastIndex)); - } - - return sb.toString(); - } - - public static String fromURLSafe(String base64) { - return StringUtil.replace( - base64, - new String[] { - StringPool.MINUS, - StringPool.STAR, - StringPool.UNDERLINE - }, - new String[] { - StringPool.PLUS, - StringPool.EQUAL, - StringPool.SLASH - }); - } - - public static String objectToString(Object o) { - if (o == null) { - return null; - } - - UnsyncByteArrayOutputStream ubaos = new UnsyncByteArrayOutputStream( - 32000); - - try { - ObjectOutputStream os = new ObjectOutputStream(ubaos); - - os.flush(); - os.writeObject(o); - os.flush(); - } - catch (Exception e) { - _log.error(e, e); - } - - return encode(ubaos.unsafeGetByteArray(), 0, ubaos.size()); - } - - public static Object stringToObject(String s) { - return _stringToObject(s, null, false); - } - - public static Object stringToObject(String s, ClassLoader classLoader) { - return _stringToObject(s, classLoader, false); - } - - public static Object stringToObjectSilent(String s) { - return _stringToObject(s, null, true); - } - - public static Object stringToObjectSilent( - String s, ClassLoader classLoader) { - - return _stringToObject(s, classLoader, true); - } - - public static String toURLSafe(String base64) { - return StringUtil.replace( - base64, - new String[] { - StringPool.PLUS, - StringPool.EQUAL, - StringPool.SLASH - }, - new String[] { - StringPool.MINUS, - StringPool.STAR, - StringPool.UNDERLINE - }); - } - - protected static char[] encodeBlock(byte raw[], int offset, int lastIndex) { - int block = 0; - int slack = lastIndex - offset - 1; - int end = slack < 2 ? slack : 2; - - for (int i = 0; i <= end; i++) { - byte b = raw[offset + i]; - - int neuter = b >= 0 ? ((int) (b)) : b + 256; - block += neuter << 8 * (2 - i); - } - - char base64[] = new char[4]; - - for (int i = 0; i < 4; i++) { - int sixbit = block >>> 6 * (3 - i) & 0x3f; - base64[i] = getChar(sixbit); - } - - if (slack < 1) { - base64[2] = CharPool.EQUAL; - } - - if (slack < 2) { - base64[3] = CharPool.EQUAL; - } - - return base64; - } - - protected static char getChar(int sixbit) { - if (sixbit >= 0 && sixbit <= 25) { - return (char)(65 + sixbit); - } - - if (sixbit >= 26 && sixbit <= 51) { - return (char)(97 + (sixbit - 26)); - } - - if (sixbit >= 52 && sixbit <= 61) { - return (char)(48 + (sixbit - 52)); - } - - if (sixbit == 62) { - return CharPool.PLUS; - } - - return sixbit != 63 ? CharPool.QUESTION : CharPool.SLASH; - } - - protected static int getValue(char c) { - if ((c >= CharPool.UPPER_CASE_A) && (c <= CharPool.UPPER_CASE_Z)) { - return c - 65; - } - - if ((c >= CharPool.LOWER_CASE_A) && (c <= CharPool.LOWER_CASE_Z)) { - return (c - 97) + 26; - } - - if (c >= CharPool.NUMBER_0 && c <= CharPool.NUMBER_9) { - return (c - 48) + 52; - } - - if (c == CharPool.PLUS) { - return 62; - } - - if (c == CharPool.SLASH) { - return 63; - } - - return c != CharPool.EQUAL ? -1 : 0; - } - - private static Object _stringToObject( - String s, ClassLoader classLoader, boolean silent) { - - if (s == null) { - return null; - } - - byte bytes[] = decode(s); - - UnsyncByteArrayInputStream ubais = new UnsyncByteArrayInputStream( - bytes); - - try { - ObjectInputStream is = null; - - if (classLoader == null) { - is = new ObjectInputStream(ubais); - } - else { - is = new ClassLoaderObjectInputStream(ubais, classLoader); - } - - return is.readObject(); - } - catch (Exception e) { - if (!silent) { - _log.error(e, e); - } - } - - return null; - } - - private static Log _log = LogFactoryUtil.getLog(Base64.class); - +/** + * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or modify it under + * the terms of the GNU Lesser General Public License as published by the Free + * Software Foundation; either version 2.1 of the License, or (at your option) + * any later version. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more + * details. + */ + +package com.liferay.portal.kernel.util; + +import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream; +import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream; +import com.liferay.portal.kernel.log.Log; +import com.liferay.portal.kernel.log.LogFactoryUtil; + +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +/** + * @author Brian Wing Shun Chan + */ +public class Base64 { + + public static byte[] decode(String base64) { + if (Validator.isNull(base64)) { + return new byte[0]; + } + + int pad = 0; + + for (int i = base64.length() - 1; base64.charAt(i) == CharPool.EQUAL; + i--) { + + pad++; + } + + int length = (base64.length() * 6) / 8 - pad; + byte raw[] = new byte[length]; + int rawindex = 0; + + for (int i = 0; i < base64.length(); i += 4) { + int block = (getValue(base64.charAt(i)) << 18) + + (getValue(base64.charAt(i + 1)) << 12) + + (getValue(base64.charAt(i + 2)) << 6) + + getValue(base64.charAt(i + 3)); + + for (int j = 0; j < 3 && rawindex + j < raw.length; j++) { + raw[rawindex + j] = (byte)(block >> 8 * (2 - j) & 0xff); + } + + rawindex += 3; + } + + return raw; + } + + public static String encode(byte raw[]) { + return encode(raw, 0, raw.length); + } + + public static String encode(byte raw[], int offset, int length) { + int lastIndex = Math.min(raw.length, offset + length); + + StringBuilder sb = new StringBuilder( + ((lastIndex - offset) / 3 + 1) * 4); + + for (int i = offset; i < lastIndex; i += 3) { + sb.append(encodeBlock(raw, i, lastIndex)); + } + + return sb.toString(); + } + + public static String fromURLSafe(String base64) { + return StringUtil.replace( + base64, + new String[] { + StringPool.MINUS, StringPool.STAR, StringPool.UNDERLINE + }, + new String[] { + StringPool.PLUS, StringPool.EQUAL, StringPool.SLASH + }); + } + + public static String objectToString(Object o) { + if (o == null) { + return null; + } + + UnsyncByteArrayOutputStream ubaos = new UnsyncByteArrayOutputStream( + 32000); + + try { + ObjectOutputStream os = new ObjectOutputStream(ubaos); + + os.flush(); + os.writeObject(o); + os.flush(); + } + catch (Exception e) { + _log.error(e, e); + } + + return encode(ubaos.unsafeGetByteArray(), 0, ubaos.size()); + } + + public static Object stringToObject(String s) { + return _stringToObject(s, null, false); + } + + public static Object stringToObject(String s, ClassLoader classLoader) { + return _stringToObject(s, classLoader, false); + } + + public static Object stringToObjectSilent(String s) { + return _stringToObject(s, null, true); + } + + public static Object stringToObjectSilent( + String s, ClassLoader classLoader) { + + return _stringToObject(s, classLoader, true); + } + + public static String toURLSafe(String base64) { + return StringUtil.replace( + base64, + new String[] { + StringPool.PLUS, StringPool.EQUAL, StringPool.SLASH + }, + new String[] { + StringPool.MINUS, StringPool.STAR, StringPool.UNDERLINE + }); + } + + protected static char[] encodeBlock(byte raw[], int offset, int lastIndex) { + int block = 0; + int slack = lastIndex - offset - 1; + int end = slack < 2 ? slack : 2; + + for (int i = 0; i <= end; i++) { + byte b = raw[offset + i]; + + int neuter = b >= 0 ? ((int) (b)) : b + 256; + block += neuter << 8 * (2 - i); + } + + char base64[] = new char[4]; + + for (int i = 0; i < 4; i++) { + int sixbit = block >>> 6 * (3 - i) & 0x3f; + base64[i] = getChar(sixbit); + } + + if (slack < 1) { + base64[2] = CharPool.EQUAL; + } + + if (slack < 2) { + base64[3] = CharPool.EQUAL; + } + + return base64; + } + + protected static char getChar(int sixbit) { + if (sixbit >= 0 && sixbit <= 25) { + return (char)(65 + sixbit); + } + + if (sixbit >= 26 && sixbit <= 51) { + return (char)(97 + (sixbit - 26)); + } + + if (sixbit >= 52 && sixbit <= 61) { + return (char)(48 + (sixbit - 52)); + } + + if (sixbit == 62) { + return CharPool.PLUS; + } + + return sixbit != 63 ? CharPool.QUESTION : CharPool.SLASH; + } + + protected static int getValue(char c) { + if ((c >= CharPool.UPPER_CASE_A) && (c <= CharPool.UPPER_CASE_Z)) { + return c - 65; + } + + if ((c >= CharPool.LOWER_CASE_A) && (c <= CharPool.LOWER_CASE_Z)) { + return (c - 97) + 26; + } + + if (c >= CharPool.NUMBER_0 && c <= CharPool.NUMBER_9) { + return (c - 48) + 52; + } + + if (c == CharPool.PLUS) { + return 62; + } + + if (c == CharPool.SLASH) { + return 63; + } + + return c != CharPool.EQUAL ? -1 : 0; + } + + private static Object _stringToObject( + String s, ClassLoader classLoader, boolean silent) { + + if (s == null) { + return null; + } + + byte bytes[] = decode(s); + + UnsyncByteArrayInputStream ubais = new UnsyncByteArrayInputStream( + bytes); + + try { + ObjectInputStream is = null; + + if (classLoader == null) { + is = new ObjectInputStream(ubais); + } + else { + is = new ClassLoaderObjectInputStream(ubais, classLoader); + } + + return is.readObject(); + } + catch (Exception e) { + if (!silent) { + _log.error(e, e); + } + } + + return null; + } + + private static Log _log = LogFactoryUtil.getLog(Base64.class); + } \ No newline at end of file diff --git a/portal-service/src/com/liferay/portal/kernel/util/StreamUtil.java b/portal-service/src/com/liferay/portal/kernel/util/StreamUtil.java index 41cca47fa81dfc..0a4be20adc835d 100644 --- a/portal-service/src/com/liferay/portal/kernel/util/StreamUtil.java +++ b/portal-service/src/com/liferay/portal/kernel/util/StreamUtil.java @@ -33,8 +33,7 @@ public class StreamUtil { public static final int BUFFER_SIZE = GetterUtil.getInteger( - System.getProperty(StreamUtil.class.getName() + ".buffer.size"), - 8192); + System.getProperty(StreamUtil.class.getName() + ".buffer.size"), 8192); public static final boolean FORCE_TIO = GetterUtil.getBoolean( System.getProperty(StreamUtil.class.getName() + ".force.tio")); diff --git a/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowDefinitionManagerUtil.java b/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowDefinitionManagerUtil.java index 9777ceb08a3af7..b152ec4ef55ec0 100644 --- a/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowDefinitionManagerUtil.java +++ b/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowDefinitionManagerUtil.java @@ -139,8 +139,7 @@ public static WorkflowDefinition updateActive( } public static WorkflowDefinition updateTitle( - long companyId, long userId, String name, int version, - String title) + long companyId, long userId, String name, int version, String title) throws WorkflowException { return _workflowDefinitionManager.updateTitle( diff --git a/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowInstanceManager.java b/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowInstanceManager.java index 2cb3f01e5077c4..39c38029c0f386 100644 --- a/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowInstanceManager.java +++ b/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowInstanceManager.java @@ -60,8 +60,8 @@ public int getWorkflowInstanceCount( public List getWorkflowInstances( long companyId, Long userId, String assetClassName, - Long assetClassPK, Boolean completed, int start, - int end, OrderByComparator orderByComparator) + Long assetClassPK, Boolean completed, int start, int end, + OrderByComparator orderByComparator) throws WorkflowException; public List getWorkflowInstances( diff --git a/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowInstanceManagerUtil.java b/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowInstanceManagerUtil.java index c2c3074ab66347..a69a85d975ec7f 100644 --- a/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowInstanceManagerUtil.java +++ b/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowInstanceManagerUtil.java @@ -87,13 +87,13 @@ public static WorkflowInstanceManager getWorkflowInstanceManager() { public static List getWorkflowInstances( long companyId, Long userId, String assetClassName, - Long assetClassPK, Boolean completed, int start, - int end, OrderByComparator orderByComparator) + Long assetClassPK, Boolean completed, int start, int end, + OrderByComparator orderByComparator) throws WorkflowException { return _workflowInstanceManager.getWorkflowInstances( - companyId, userId, assetClassName, assetClassPK, - completed, start, end, orderByComparator); + companyId, userId, assetClassName, assetClassPK, completed, start, + end, orderByComparator); } public static List getWorkflowInstances( @@ -114,9 +114,8 @@ public static List getWorkflowInstances( throws WorkflowException { return _workflowInstanceManager.getWorkflowInstances( - companyId, workflowDefinitionName, - workflowDefinitionVersion, completed, start, - end, orderByComparator); + companyId, workflowDefinitionName, workflowDefinitionVersion, + completed, start, end, orderByComparator); } public static WorkflowInstance signalWorkflowInstance( diff --git a/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowLogManagerUtil.java b/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowLogManagerUtil.java index 82b63e20896bf8..c5d098724ef5b5 100644 --- a/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowLogManagerUtil.java +++ b/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowLogManagerUtil.java @@ -51,8 +51,8 @@ public static List getWorkflowLogsByWorkflowInstance( throws WorkflowException { return _workflowLogManager.getWorkflowLogsByWorkflowInstance( - companyId, workflowInstanceId, logTypes, - start, end, orderByComparator); + companyId, workflowInstanceId, logTypes, start, end, + orderByComparator); } public static List getWorkflowLogsByWorkflowTask( @@ -61,8 +61,7 @@ public static List getWorkflowLogsByWorkflowTask( throws WorkflowException { return _workflowLogManager.getWorkflowLogsByWorkflowTask( - companyId, workflowTaskId, logTypes, - start, end, orderByComparator); + companyId, workflowTaskId, logTypes, start, end, orderByComparator); } public void setWorkflowLogManager(WorkflowLogManager workflowLogManager) { diff --git a/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowTaskManager.java b/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowTaskManager.java index 60e0d46fc0a0e6..de0878ff8f53ae 100644 --- a/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowTaskManager.java +++ b/portal-service/src/com/liferay/portal/kernel/workflow/WorkflowTaskManager.java @@ -117,8 +117,8 @@ public List getWorkflowTasksByWorkflowInstance( throws WorkflowException; public List search( - long companyId, long userId, String keywords, - Boolean completed, Boolean searchByUserRoles, int start, int end, + long companyId, long userId, String keywords, Boolean completed, + Boolean searchByUserRoles, int start, int end, OrderByComparator orderByComparator) throws WorkflowException; diff --git a/portal-service/src/com/liferay/portal/model/LayoutSetStagingHandler.java b/portal-service/src/com/liferay/portal/model/LayoutSetStagingHandler.java index b336f280bf316a..a2d404ec7fea0b 100644 --- a/portal-service/src/com/liferay/portal/model/LayoutSetStagingHandler.java +++ b/portal-service/src/com/liferay/portal/model/LayoutSetStagingHandler.java @@ -137,8 +137,7 @@ private LayoutSetBranch _getLayoutSetBranch(LayoutSet layoutSet) private Object _toEscapedModel() { return ProxyUtil.newProxyInstance( - PortalClassLoaderUtil.getClassLoader(), - new Class[] {Layout.class}, + PortalClassLoaderUtil.getClassLoader(), new Class[] {Layout.class}, new LayoutSetStagingHandler(_layoutSet.toEscapedModel())); } diff --git a/portal-service/src/com/liferay/portal/model/LayoutStagingHandler.java b/portal-service/src/com/liferay/portal/model/LayoutStagingHandler.java index 35a6e43e03791b..7f045bcb4a0ac3 100644 --- a/portal-service/src/com/liferay/portal/model/LayoutStagingHandler.java +++ b/portal-service/src/com/liferay/portal/model/LayoutStagingHandler.java @@ -291,8 +291,7 @@ private LayoutType _getLayoutType() { private Object _toEscapedModel() { return ProxyUtil.newProxyInstance( - PortalClassLoaderUtil.getClassLoader(), - new Class[] {Layout.class}, + PortalClassLoaderUtil.getClassLoader(), new Class[] {Layout.class}, new LayoutStagingHandler( _layout.toEscapedModel(), _layoutRevision.toEscapedModel())); } diff --git a/portal-service/src/com/liferay/portal/security/permission/BasePermissionPropagator.java b/portal-service/src/com/liferay/portal/security/permission/BasePermissionPropagator.java index b4e09a6c726a25..ca782eb3dbc9b8 100644 --- a/portal-service/src/com/liferay/portal/security/permission/BasePermissionPropagator.java +++ b/portal-service/src/com/liferay/portal/security/permission/BasePermissionPropagator.java @@ -74,11 +74,11 @@ protected void propagateRolePermissions( } Set parentAvailableActionIds = getAvailableActionIds( - themeDisplay.getCompanyId(), parentClassName, - parentPrimKey, roleId, parentActionIds); + themeDisplay.getCompanyId(), parentClassName, parentPrimKey, roleId, + parentActionIds); Set childAvailableActionIds = getAvailableActionIds( - themeDisplay.getCompanyId(), childClassName, - childPrimKey, roleId, childActionIds); + themeDisplay.getCompanyId(), childClassName, childPrimKey, roleId, + childActionIds); List actionIds = new ArrayList(); diff --git a/portal-service/src/com/liferay/portal/service/permission/GroupPermission.java b/portal-service/src/com/liferay/portal/service/permission/GroupPermission.java index c5868f90332ada..293011b9196406 100644 --- a/portal-service/src/com/liferay/portal/service/permission/GroupPermission.java +++ b/portal-service/src/com/liferay/portal/service/permission/GroupPermission.java @@ -24,8 +24,7 @@ public interface GroupPermission { public void check( - PermissionChecker permissionChecker, long groupId, - String actionId) + PermissionChecker permissionChecker, long groupId, String actionId) throws PortalException, SystemException; public boolean contains( diff --git a/portal-service/src/com/liferay/portal/service/permission/LayoutBranchPermission.java b/portal-service/src/com/liferay/portal/service/permission/LayoutBranchPermission.java index adaffcb737881b..717e77faa38aeb 100644 --- a/portal-service/src/com/liferay/portal/service/permission/LayoutBranchPermission.java +++ b/portal-service/src/com/liferay/portal/service/permission/LayoutBranchPermission.java @@ -26,8 +26,8 @@ public interface LayoutBranchPermission { public void check( - PermissionChecker permissionChecker, - LayoutBranch layoutBranch, String actionId) + PermissionChecker permissionChecker, LayoutBranch layoutBranch, + String actionId) throws PortalException; public void check( diff --git a/portal-service/src/com/liferay/portal/service/permission/LayoutBranchPermissionUtil.java b/portal-service/src/com/liferay/portal/service/permission/LayoutBranchPermissionUtil.java index be1632f3071d6c..703917e0607b78 100644 --- a/portal-service/src/com/liferay/portal/service/permission/LayoutBranchPermissionUtil.java +++ b/portal-service/src/com/liferay/portal/service/permission/LayoutBranchPermissionUtil.java @@ -26,8 +26,8 @@ public class LayoutBranchPermissionUtil { public static void check( - PermissionChecker permissionChecker, - LayoutBranch layoutBranch, String actionId) + PermissionChecker permissionChecker, LayoutBranch layoutBranch, + String actionId) throws PortalException { getLayoutBranchPermission().check( diff --git a/portal-service/src/com/liferay/portal/service/permission/UserGroupPermission.java b/portal-service/src/com/liferay/portal/service/permission/UserGroupPermission.java index 8a11a158f86e2c..9046a2ec65006b 100644 --- a/portal-service/src/com/liferay/portal/service/permission/UserGroupPermission.java +++ b/portal-service/src/com/liferay/portal/service/permission/UserGroupPermission.java @@ -28,7 +28,6 @@ public void check( throws PrincipalException; public boolean contains( - PermissionChecker permissionChecker, long userGroupId, - String actionId); + PermissionChecker permissionChecker, long userGroupId, String actionId); } \ No newline at end of file diff --git a/portal-service/src/com/liferay/portal/util/SubscriptionSender.java b/portal-service/src/com/liferay/portal/util/SubscriptionSender.java index b8dbca924421d4..53b798e33e129f 100644 --- a/portal-service/src/com/liferay/portal/util/SubscriptionSender.java +++ b/portal-service/src/com/liferay/portal/util/SubscriptionSender.java @@ -471,9 +471,7 @@ protected void processMailMessage(MailMessage mailMessage, Locale locale) String processedSubject = StringUtil.replace( mailMessage.getSubject(), new String[] { - "[$FROM_ADDRESS$]", - "[$FROM_NAME$]", - "[$TO_ADDRESS$]", + "[$FROM_ADDRESS$]", "[$FROM_NAME$]", "[$TO_ADDRESS$]", "[$TO_NAME$]" }, new String[] { @@ -491,9 +489,7 @@ protected void processMailMessage(MailMessage mailMessage, Locale locale) String processedBody = StringUtil.replace( mailMessage.getBody(), new String[] { - "[$FROM_ADDRESS$]", - "[$FROM_NAME$]", - "[$TO_ADDRESS$]", + "[$FROM_ADDRESS$]", "[$FROM_NAME$]", "[$TO_ADDRESS$]", "[$TO_NAME$]" }, new String[] { diff --git a/portal-service/src/com/liferay/portlet/documentlibrary/store/BaseStore.java b/portal-service/src/com/liferay/portlet/documentlibrary/store/BaseStore.java index 1927aa50e2da03..d6329b434b84ec 100644 --- a/portal-service/src/com/liferay/portlet/documentlibrary/store/BaseStore.java +++ b/portal-service/src/com/liferay/portlet/documentlibrary/store/BaseStore.java @@ -476,8 +476,8 @@ public abstract void move(String srcDir, String destDir) * @throws SystemException if a system exception occurred */ public abstract void updateFile( - long companyId, long repositoryId, - long newRepositoryId, String fileName) + long companyId, long repositoryId, long newRepositoryId, + String fileName) throws PortalException, SystemException; /** diff --git a/portal-service/src/com/liferay/portlet/documentlibrary/util/DLPreviewableProcessor.java b/portal-service/src/com/liferay/portlet/documentlibrary/util/DLPreviewableProcessor.java index 9c442cbfcefd6b..29e58212762454 100644 --- a/portal-service/src/com/liferay/portlet/documentlibrary/util/DLPreviewableProcessor.java +++ b/portal-service/src/com/liferay/portlet/documentlibrary/util/DLPreviewableProcessor.java @@ -397,8 +397,7 @@ protected void exportThumbnails( } protected String getBinPath( - PortletDataContext portletDataContext, FileEntry fileEntry, - int index) { + PortletDataContext portletDataContext, FileEntry fileEntry, int index) { StringBundler sb = new StringBundler(8); diff --git a/portal-service/src/com/liferay/portlet/documentlibrary/util/DLUtil.java b/portal-service/src/com/liferay/portlet/documentlibrary/util/DLUtil.java index 8ba6d53dfb33ad..4a6804f2908989 100644 --- a/portal-service/src/com/liferay/portlet/documentlibrary/util/DLUtil.java +++ b/portal-service/src/com/liferay/portlet/documentlibrary/util/DLUtil.java @@ -94,8 +94,7 @@ public static void addPortletBreadcrumbEntries( portletURL.setParameter( "struts_action", "/document_library/view_file_entry"); portletURL.setParameter( - "fileEntryId", - String.valueOf(dlFileShortcut.getToFileEntryId())); + "fileEntryId", String.valueOf(dlFileShortcut.getToFileEntryId())); PortalUtil.addPortletBreadcrumbEntry( request, dlFileShortcut.getToTitle(), portletURL.toString()); diff --git a/portal-service/src/com/liferay/portlet/documentlibrary/util/ImageProcessor.java b/portal-service/src/com/liferay/portlet/documentlibrary/util/ImageProcessor.java index f7f412c6b76cd3..630bffe169137d 100644 --- a/portal-service/src/com/liferay/portlet/documentlibrary/util/ImageProcessor.java +++ b/portal-service/src/com/liferay/portlet/documentlibrary/util/ImageProcessor.java @@ -62,8 +62,8 @@ public void importGeneratedFiles( public void storeThumbnail( long companyId, long groupId, long fileEntryId, long fileVersionId, - long custom1ImageId, long custom2ImageId, - InputStream is, String type) + long custom1ImageId, long custom2ImageId, InputStream is, + String type) throws Exception; public void trigger(FileVersion fileVersion); diff --git a/portal-service/src/com/liferay/portlet/documentlibrary/util/ImageProcessorUtil.java b/portal-service/src/com/liferay/portlet/documentlibrary/util/ImageProcessorUtil.java index 90dffaa0c306bd..266521c4063f49 100644 --- a/portal-service/src/com/liferay/portlet/documentlibrary/util/ImageProcessorUtil.java +++ b/portal-service/src/com/liferay/portlet/documentlibrary/util/ImageProcessorUtil.java @@ -77,8 +77,8 @@ public static boolean isSupported(String mimeType) { public static void storeThumbnail( long companyId, long groupId, long fileEntryId, long fileVersionId, - long custom1ImageId, long custom2ImageId, - InputStream is, String type) + long custom1ImageId, long custom2ImageId, InputStream is, + String type) throws Exception { getImageProcessor().storeThumbnail( diff --git a/portal-service/src/com/liferay/portlet/dynamicdatamapping/storage/BaseStorageAdapter.java b/portal-service/src/com/liferay/portlet/dynamicdatamapping/storage/BaseStorageAdapter.java index a098218405f932..c8e8c2d5ba2da1 100644 --- a/portal-service/src/com/liferay/portlet/dynamicdatamapping/storage/BaseStorageAdapter.java +++ b/portal-service/src/com/liferay/portlet/dynamicdatamapping/storage/BaseStorageAdapter.java @@ -95,8 +95,8 @@ public Fields getFields(long classPK, List fieldNames) DDMStorageLinkLocalServiceUtil.getClassStorageLink(classPK); Map fieldsMapByClasses = getFieldsMap( - ddmStorageLink.getStructureId(), - new long[] {classPK}, fieldNames); + ddmStorageLink.getStructureId(), new long[] {classPK}, + fieldNames); return fieldsMapByClasses.get(classPK); } diff --git a/portal-service/src/com/liferay/portlet/expando/service/permission/ExpandoColumnPermissionUtil.java b/portal-service/src/com/liferay/portlet/expando/service/permission/ExpandoColumnPermissionUtil.java index 60f71b0c294949..f5e19600d4262f 100644 --- a/portal-service/src/com/liferay/portlet/expando/service/permission/ExpandoColumnPermissionUtil.java +++ b/portal-service/src/com/liferay/portlet/expando/service/permission/ExpandoColumnPermissionUtil.java @@ -47,8 +47,8 @@ public static void check( throws PortalException, SystemException { getExpandoColumnPermission().check( - permissionChecker, companyId, className, tableName, - columnName, actionId); + permissionChecker, companyId, className, tableName, columnName, + actionId); } public static boolean contains( @@ -74,8 +74,8 @@ public static boolean contains( throws SystemException { return getExpandoColumnPermission().contains( - permissionChecker, companyId, className, tableName, - columnName, actionId); + permissionChecker, companyId, className, tableName, columnName, + actionId); } public static ExpandoColumnPermission getExpandoColumnPermission() { diff --git a/portal-service/src/com/liferay/portlet/social/model/SocialActivityDefinition.java b/portal-service/src/com/liferay/portlet/social/model/SocialActivityDefinition.java index dbf2af42a91714..9293eb57e25ed2 100644 --- a/portal-service/src/com/liferay/portlet/social/model/SocialActivityDefinition.java +++ b/portal-service/src/com/liferay/portlet/social/model/SocialActivityDefinition.java @@ -97,8 +97,7 @@ public String getModelName() { public String getName(Locale locale) { return LanguageUtil.get( - locale, - "social.activity." + _modelName + "." + _languageKey); + locale, "social.activity." + _modelName + "." + _languageKey); } public boolean isEnabled() { diff --git a/portal-service/test/com/liferay/portal/kernel/cal/TZSRecurrenceTest.java b/portal-service/test/com/liferay/portal/kernel/cal/TZSRecurrenceTest.java index 94d8954b74b4b1..21fcc081d6df34 100644 --- a/portal-service/test/com/liferay/portal/kernel/cal/TZSRecurrenceTest.java +++ b/portal-service/test/com/liferay/portal/kernel/cal/TZSRecurrenceTest.java @@ -45,8 +45,7 @@ public void testInsideDSTTZSRecurrence() { testWithinTSZRecurrence( getInsideDSTCalendar(AUGUST, 7), _durationHour, firstSunOfMonth); testWithinTSZRecurrence( - getInsideDSTCalendar(DECEMBER, 4), _durationHour, - firstSunOfMonth); + getInsideDSTCalendar(DECEMBER, 4), _durationHour, firstSunOfMonth); // Events starting inside DST matched second day of the month diff --git a/portal-service/test/com/liferay/portal/kernel/concurrent/ThreadPoolExecutorTest.java b/portal-service/test/com/liferay/portal/kernel/concurrent/ThreadPoolExecutorTest.java index 64e73bdbbc93ef..80267afb176b29 100644 --- a/portal-service/test/com/liferay/portal/kernel/concurrent/ThreadPoolExecutorTest.java +++ b/portal-service/test/com/liferay/portal/kernel/concurrent/ThreadPoolExecutorTest.java @@ -952,8 +952,7 @@ public void testExecute6() throws InterruptedException { assertEquals(1, threadPoolExecutor.getLargestPoolSize()); assertEquals( - 10, - recordUncaughtExceptionHandler.getUncaughtMap().size()); + 10, recordUncaughtExceptionHandler.getUncaughtMap().size()); for (MarkerBlockingJob markerBlockingJob : markerBlockingJobQueue) { assertTrue(markerBlockingJob.isStarted()); diff --git a/util-bridges/src/com/liferay/util/bridges/jsf/myfaces/MyFacesContextFactoryImpl.java b/util-bridges/src/com/liferay/util/bridges/jsf/myfaces/MyFacesContextFactoryImpl.java index 280a2106fe40be..2d7c90c6b3aec2 100644 --- a/util-bridges/src/com/liferay/util/bridges/jsf/myfaces/MyFacesContextFactoryImpl.java +++ b/util-bridges/src/com/liferay/util/bridges/jsf/myfaces/MyFacesContextFactoryImpl.java @@ -58,8 +58,7 @@ public FacesContext getFacesContext( if (context instanceof ServletContext) { return new ServletFacesContextImpl( - (ServletContext)context, - (ServletRequest)request, + (ServletContext)context, (ServletRequest)request, (ServletResponse)response); } diff --git a/util-java/src/com/liferay/util/axis/AxisServlet.java b/util-java/src/com/liferay/util/axis/AxisServlet.java index e73e9faec7ec77..7f3ffb18207c8f 100644 --- a/util-java/src/com/liferay/util/axis/AxisServlet.java +++ b/util-java/src/com/liferay/util/axis/AxisServlet.java @@ -187,20 +187,12 @@ protected String fixXml(String xml) throws Exception { xml = StringUtil.replace( xml, new String[] { - "\r\n", - "\n", - " ", - "> <", - _INCORRECT_LONG_ARRAY, + "\r\n", "\n", " ", "> <", _INCORRECT_LONG_ARRAY, _INCORRECT_STRING_ARRAY }, new String[] { - StringPool.BLANK, - StringPool.BLANK, - StringPool.BLANK, - "><", - _CORRECT_LONG_ARRAY, - _CORRECT_STRING_ARRAY + StringPool.BLANK, StringPool.BLANK, StringPool.BLANK, "><", + _CORRECT_LONG_ARRAY, _CORRECT_STRING_ARRAY }); Document document = SAXReaderUtil.read(xml); diff --git a/util-java/src/com/liferay/util/dao/orm/CustomSQL.java b/util-java/src/com/liferay/util/dao/orm/CustomSQL.java index 5a45f82cb22694..a4c616fc26735b 100644 --- a/util-java/src/com/liferay/util/dao/orm/CustomSQL.java +++ b/util-java/src/com/liferay/util/dao/orm/CustomSQL.java @@ -395,8 +395,7 @@ public String replaceAndOperator(String sql, boolean andOperator) { new String[] { "Date >= ? AND ? IS NOT NULL", "Date <= ? AND ? IS NOT NULL", - "Date >= ? OR ? IS NULL", - "Date <= ? OR ? IS NULL" + "Date >= ? OR ? IS NULL", "Date <= ? OR ? IS NULL" }, new String[] { "Date >= ? AND CAST(? AS TIMESTAMP) IS NOT NULL", @@ -459,8 +458,7 @@ public String replaceIsNull(String sql) { "? IS NULL", "? IS NOT NULL" }, new String[] { - _functionIsNull, - _functionIsNotNull + _functionIsNull, _functionIsNotNull }); } diff --git a/util-java/src/com/liferay/util/diff/DiffUtil.java b/util-java/src/com/liferay/util/diff/DiffUtil.java index 98e6739146fb8e..1c8a60a341d2fd 100644 --- a/util-java/src/com/liferay/util/diff/DiffUtil.java +++ b/util-java/src/com/liferay/util/diff/DiffUtil.java @@ -106,9 +106,8 @@ public static List[] diff( // Lines were deleted from source only. _highlightLines( - sourceStringList, deletedMarkerStart, - deletedMarkerEnd, difference.getDeletedStart(), - difference.getDeletedEnd()); + sourceStringList, deletedMarkerStart, deletedMarkerEnd, + difference.getDeletedStart(), difference.getDeletedEnd()); margin = _calculateMargin( sourceResults, targetResults, difference.getDeletedStart(), @@ -464,9 +463,8 @@ private static boolean _lineDiff( // Chars were deleted from source only. _highlightChars( - sourceList, deletedMarkerStart, - deletedMarkerEnd, difference.getDeletedStart(), - difference.getDeletedEnd()); + sourceList, deletedMarkerStart, deletedMarkerEnd, + difference.getDeletedStart(), difference.getDeletedEnd()); sourceChanged = true; } @@ -485,9 +483,8 @@ else if (difference.getDeletedEnd() == Difference.NONE) { // Chars were both deleted and added. _highlightChars( - sourceList, deletedMarkerStart, - deletedMarkerEnd, difference.getDeletedStart(), - difference.getDeletedEnd()); + sourceList, deletedMarkerStart, deletedMarkerEnd, + difference.getDeletedStart(), difference.getDeletedEnd()); sourceChanged = true; diff --git a/util-java/src/com/liferay/util/xml/XMLFormatter.java b/util-java/src/com/liferay/util/xml/XMLFormatter.java index c80138b7f7d0a4..b731d39b1e1e12 100644 --- a/util-java/src/com/liferay/util/xml/XMLFormatter.java +++ b/util-java/src/com/liferay/util/xml/XMLFormatter.java @@ -84,14 +84,11 @@ public static String toCompactSafe(String xml) { return StringUtil.replace( xml, new String[] { - StringPool.RETURN_NEW_LINE, - StringPool.NEW_LINE, + StringPool.RETURN_NEW_LINE, StringPool.NEW_LINE, StringPool.RETURN }, new String[] { - "[$NEW_LINE$]", - "[$NEW_LINE$]", - "[$NEW_LINE$]" + "[$NEW_LINE$]", "[$NEW_LINE$]", "[$NEW_LINE$]" }); } diff --git a/util-taglib/src/com/liferay/taglib/ui/CustomAttributesAvailableTag.java b/util-taglib/src/com/liferay/taglib/ui/CustomAttributesAvailableTag.java index f8824b750ed52c..341327786f0944 100644 --- a/util-taglib/src/com/liferay/taglib/ui/CustomAttributesAvailableTag.java +++ b/util-taglib/src/com/liferay/taglib/ui/CustomAttributesAvailableTag.java @@ -116,8 +116,8 @@ public int doStartTag() throws JspException { if (!propertyHidden && ExpandoColumnPermissionUtil.contains( permissionChecker, companyId, _className, - ExpandoTableConstants.DEFAULT_TABLE_NAME, - attributeName, ActionKeys.VIEW)) { + ExpandoTableConstants.DEFAULT_TABLE_NAME, attributeName, + ActionKeys.VIEW)) { return EVAL_BODY_INCLUDE; } diff --git a/util-taglib/src/com/liferay/taglib/ui/SearchContainerTei.java b/util-taglib/src/com/liferay/taglib/ui/SearchContainerTei.java index a698f2b02cd4f8..fd6cab76dd2e39 100644 --- a/util-taglib/src/com/liferay/taglib/ui/SearchContainerTei.java +++ b/util-taglib/src/com/liferay/taglib/ui/SearchContainerTei.java @@ -36,8 +36,7 @@ public VariableInfo[] getVariableInfo(TagData tagData) { return new VariableInfo[] { new VariableInfo( - var, SearchContainer.class.getName(), true, - VariableInfo.NESTED) + var, SearchContainer.class.getName(), true, VariableInfo.NESTED) }; } diff --git a/util-taglib/src/com/liferay/taglib/util/VelocityTaglib.java b/util-taglib/src/com/liferay/taglib/util/VelocityTaglib.java index 55046235f07728..9d1cc0a4b86115 100644 --- a/util-taglib/src/com/liferay/taglib/util/VelocityTaglib.java +++ b/util-taglib/src/com/liferay/taglib/util/VelocityTaglib.java @@ -512,8 +512,8 @@ public void renderURL(String portletName, String queryString) public void renderURL( String windowState, String portletMode, Boolean secure, - Boolean copyCurrentRenderParameters, Boolean escapeXml, - long plid, long refererPlid, String portletName, Boolean anchor, + Boolean copyCurrentRenderParameters, Boolean escapeXml, long plid, + long refererPlid, String portletName, Boolean anchor, Boolean encrypt, long doAsGroupId, long doAsUserId, Boolean portletConfiguration, String queryString) throws Exception { @@ -541,8 +541,8 @@ public void renderURL( */ public void renderURL( String windowState, String portletMode, Boolean secure, - Boolean copyCurrentRenderParameters, Boolean escapeXml, - long plid, String portletName, Boolean anchor, Boolean encrypt, + Boolean copyCurrentRenderParameters, Boolean escapeXml, long plid, + String portletName, Boolean anchor, Boolean encrypt, long doAsUserId, Boolean portletConfiguration, String queryString) throws Exception {