• liferay项目经验之BasePortlet


    package com.ebizwindow.crm.portlet.base;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Locale;
    import java.util.Map;
    import java.util.Set;
    
    import javax.portlet.ActionRequest;
    import javax.portlet.ActionResponse;
    import javax.portlet.GenericPortlet;
    import javax.portlet.PortletException;
    import javax.portlet.PortletMode;
    import javax.portlet.PortletPreferences;
    import javax.portlet.PortletRequest;
    import javax.portlet.PortletRequestDispatcher;
    import javax.portlet.PortletURL;
    import javax.portlet.RenderRequest;
    import javax.portlet.RenderResponse;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.ebizwindow.crm.NoSuchTableDefinitionException;
    import com.ebizwindow.crm.NoSuchViewException;
    import com.ebizwindow.crm.constants.Constants;
    import com.ebizwindow.crm.constants.EntityIdConst;
    import com.ebizwindow.crm.constants.PortletIDs;
    import com.ebizwindow.crm.constants.SocialConst;
    import com.ebizwindow.crm.constants.TableConst;
    import com.ebizwindow.crm.json.JSONObject;
    import com.ebizwindow.crm.model.CompanyColumnDefinition;
    import com.ebizwindow.crm.model.View;
    import com.ebizwindow.crm.model.ViewColumn;
    import com.ebizwindow.crm.model.ViewItem;
    import com.ebizwindow.crm.portlet.settings.ViewPortlet;
    import com.ebizwindow.crm.service.CompanyColumnDefinitionLocalServiceUtil;
    import com.ebizwindow.crm.service.ViewColumnLocalServiceUtil;
    import com.ebizwindow.crm.service.ViewItemLocalServiceUtil;
    import com.ebizwindow.crm.service.ViewLocalServiceUtil;
    import com.ebizwindow.crm.utils.ActivityUtils;
    import com.ebizwindow.crm.utils.CookieUtil;
    import com.ebizwindow.crm.utils.DateUtil;
    import com.ebizwindow.crm.utils.FileEntryUtil;
    import com.ebizwindow.crm.utils.IDGenerator;
    import com.ebizwindow.crm.utils.LanguageUtil;
    import com.ebizwindow.crm.utils.LiferayUserUtil;
    import com.ebizwindow.crm.utils.PermissionUtil;
    import com.ebizwindow.crm.utils.PortletPreferencesUtil;
    import com.ebizwindow.crm.utils.PortletURLUtil;
    import com.ebizwindow.crm.utils.PrettyDateFormat;
    import com.ebizwindow.crm.utils.PropsUtil;
    import com.ebizwindow.crm.utils.SQLUtil;
    import com.ebizwindow.crm.utils.TextUtil;
    import com.ebizwindow.crm.utils.Validator;
    import com.ebizwindow.operator.model.SocialAttachment;
    import com.ebizwindow.operator.model.SocialComments;
    import com.ebizwindow.operator.model.SocialNews;
    import com.ebizwindow.operator.service.SocialAttachmentLocalServiceUtil;
    import com.ebizwindow.operator.service.SocialCommentsLocalServiceUtil;
    import com.ebizwindow.operator.service.SocialNewsLocalServiceUtil;
    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.repository.model.FileEntry;
    import com.liferay.portal.kernel.repository.model.Folder;
    import com.liferay.portal.kernel.upload.UploadRequest;
    import com.liferay.portal.kernel.util.MimeTypesUtil;
    import com.liferay.portal.kernel.util.ParamUtil;
    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.WebKeys;
    import com.liferay.portal.model.Layout;
    import com.liferay.portal.model.PortletConstants;
    import com.liferay.portal.model.RoleConstants;
    import com.liferay.portal.security.permission.ActionKeys;
    import com.liferay.portal.security.permission.PermissionChecker;
    import com.liferay.portal.service.ResourcePermissionLocalServiceUtil;
    import com.liferay.portal.service.ServiceContext;
    import com.liferay.portal.service.ServiceContextFactory;
    import com.liferay.portal.service.UserLocalServiceUtil;
    import com.liferay.portal.theme.ThemeDisplay;
    import com.liferay.portal.util.PortalUtil;
    import com.liferay.portlet.documentlibrary.FileSizeException;
    import com.liferay.portlet.documentlibrary.model.DLFileEntry;
    import com.liferay.portlet.documentlibrary.model.DLFolder;
    import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil;
    import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
    import com.liferay.portlet.documentlibrary.service.DLFolderLocalServiceUtil;
    
    /**
     * <a href="BasePortlet.java.html"><b><i>View Source</i></b></a>
     * 
     * @author Ivan Li
     * 
     */
    public abstract class BasePortlet extends GenericPortlet {
    	protected final static String FORWARD = "forward";//跳转的路径
    	protected final static String FOCUS = "focus";
    	protected final static String CHECKED = "on";
    	protected final static String CHANGE = "change";
    	protected final static String SHARE = "share";
    	protected final static String OPERATION = "operation";//操作
    
    	//存放portal数据的集合
    	protected static Set<String> PORTAL_PARAMETER_NAMES = new HashSet<String>();
    
    	static {
    		PORTAL_PARAMETER_NAMES.add("p_p_lifecycle");//周期
    		PORTAL_PARAMETER_NAMES.add("p_p_state");//周期
    		PORTAL_PARAMETER_NAMES.add("p_p_mode");//模式
    		PORTAL_PARAMETER_NAMES.add("p_p_id");//portlet的id
    	}
    
    	public void init() throws PortletException {
    		editJSP = getInitParameter("edit-jsp");
    		viewJSP = getInitParameter("view-jsp");
    		helpJSP = getInitParameter("help-jsp");
    	}
    
    	public void doDispatch(RenderRequest renderRequest,
    			RenderResponse renderResponse) throws IOException, PortletException {
    
    		super.doDispatch(renderRequest, renderResponse);
    	}
    
    	public void doEdit(RenderRequest renderRequest,
    			RenderResponse renderResponse) throws IOException, PortletException {
    		
    		String jspPage = renderRequest.getParameter(FORWARD);
    		jspPage = jspPage == null ? this.editJSP : jspPage;
    
    		include(jspPage, renderRequest, renderResponse);
    	}
    
    	public void doView(RenderRequest renderRequest,
    			RenderResponse renderResponse) throws IOException, PortletException {
    
    		String jspPage = renderRequest.getParameter(FORWARD);
    		if (jspPage == null) {
    			//用户的id
    			long userId = PortalUtil.getUserId(renderRequest);
    			if (userId == 0L) {
    				//如果没有找到用户的话,就需要找到登录的界面
    				jspPage = NEED_LOGIN_JSP;
    			} else {
    				//主题这个是干什么用的啊
    				ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest
    						.getAttribute(WebKeys.THEME_DISPLAY);
    				PermissionChecker permissionChecker = themeDisplay
    						.getPermissionChecker();
    				boolean isCompanyAdmin = permissionChecker.isCompanyAdmin();
    
    				if (!isCompanyAdmin) {
    					if (!PermissionUtil.isOperator(renderRequest)) {
    						jspPage = NOT_OPERATOR_JSP;
    					}
    				}
    			}
    		}
    		renderRequest.setAttribute(FORWARD, jspPage);
    	}
    
    	public void processAction(ActionRequest actionRequest,
    			ActionResponse actionResponse) throws IOException, PortletException {
    
    		//得到portlet的id
    		String portletId = PortalUtil.getPortletId(actionRequest);
    		actionRequest.setAttribute(FOCUS, portletId);
    		//得到操作的名称
    		String operation = ParamUtil.getString(actionRequest, OPERATION,
    				StringPool.BLANK);
    
    		String forward = null;
    		try {
    			if (!operation.equals(StringPool.BLANK)) {
    				if (operation.equals("view.load")) {
    					
    					ViewPortlet.loadView(actionRequest);
    					forward = "/jsp/tools/view/add.jsp";
    				} else if (operation.equals("view.update")) {
    					ViewPortlet.updateView(actionRequest, actionResponse);
    				} else if (operation.equals("view.remove")) {
    					ViewPortlet.removeView(actionRequest, actionResponse);
    				} else if (operation.equals("view.execute")) {
    					ViewPortlet.executeView(actionRequest, actionResponse);
    					PortletURL redirect = PortletURLUtil
    							.getPortletURL(actionRequest);
    					redirect.setPortletMode(PortletMode.VIEW);
    					actionResponse.sendRedirect(redirect.toString());
    				} else if (operation.equals("social.save.news")) {
    					this.saveNews(actionRequest, actionResponse);
    				} else if (operation.equals("social.remove.news")) {
    					this.removeNews(actionRequest, actionResponse);
    				} else if (operation.equals("social.save.comments")) {
    					this.saveComments(actionRequest, actionResponse);
    				} else if (operation.equals("social.remove.comments")) {
    					this.removeComments(actionRequest, actionResponse);
    				} else if (operation.equals("get.attathment")) {
    					this.getAttathment(actionRequest, actionResponse);
    				} else if (operation.equals("social.load.more")) {
    					this.loadMoreNews(actionRequest);
    					forward = "/jsp/common/social-clone-sub.jsp";
    				}
    			}
    		} catch (NoSuchTableDefinitionException e) {
    			_log.error(e);
    		} catch (NoSuchViewException e) {
    			_log.error(e);
    		} catch (SystemException e) {
    			_log.error(e);
    		} catch (PortalException e) {
    			_log.error(e);
    		} catch (Exception e) {
    			_log.error(e);
    		}
    
    		if (forward != null) {
    			actionResponse.setRenderParameter(FORWARD, forward);
    		}
    	}
    
    	private void loadMoreNews(ActionRequest actionRequest) throws SystemException {
    		int loadMoreMarker = ParamUtil.getInteger(actionRequest, "loadMoreMarker");
    		long companyId = PortalUtil.getCompanyId(actionRequest);
    		String module = ParamUtil.getString(actionRequest, "module", StringPool.BLANK);
    		long moduleId = ParamUtil.getLong(actionRequest, "moduleId", 0l);
    		int allNews = SocialNewsLocalServiceUtil.countByModuleId(companyId, module, moduleId);
    		int start = loadMoreMarker * 4;
    		int end = (loadMoreMarker + 1) * 4;
    		if (start >= allNews || end >= allNews) {
    			end = allNews;
    			actionRequest.setAttribute("isLoadMore", false);
    		}
    
    		if (start < allNews) {
    			List<SocialNews> socialNews = SocialNewsLocalServiceUtil.searchByModuleId(companyId, module, moduleId, start, end);
    			actionRequest.setAttribute("socialNews", socialNews);
    		}
    	}
    
    	private void getAttathment(ActionRequest actionRequest, ActionResponse actionResponse) throws PortalException, SystemException, IOException {
    		long fileEntryId = ParamUtil.getLong(actionRequest, "fileEntryId", 0l);
    		if (fileEntryId > 0) {
    			HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);
    			HttpServletRequest request = PortalUtil.getHttpServletRequest(actionRequest);
    			FileEntryUtil.downloadFileEntry(request, response, fileEntryId);
    		}
    	}
    
    	protected void include(String path, RenderRequest renderRequest,
    			RenderResponse renderResponse) throws IOException, PortletException {
    
    		PortletRequestDispatcher portletRequestDispatcher = getPortletContext()
    				.getRequestDispatcher(path);
    
    		if (portletRequestDispatcher == null) {
    			_log.error(path + " is not a valid include");
    		} else {
    			portletRequestDispatcher.include(renderRequest, renderResponse);
    		}
    	}
    
    	//组装查询的语句
    	protected String assembledQueryStatement(PortletRequest portletRequest)
    			throws SystemException, PortalException {
    		long userId = PortalUtil.getUserId(portletRequest);
    		long companyId = PortalUtil.getCompanyId(portletRequest);
    		String portletId = PortalUtil.getPortletId(portletRequest);
    		String tableName = PropsUtil.getTableNameByPortletId(portletId);
    		View view = null;
    		Cookie viewCookie = CookieUtil.getCookieByName(portletRequest, userId + "-view-" + tableName);
    		if (viewCookie != null) {
    			String viewIdString = viewCookie.getValue();
    			view = ViewLocalServiceUtil.getView(Long.valueOf(viewIdString));
    		} else {
    			view = ViewLocalServiceUtil.searchByIsDefault(companyId, tableName, true);
    		}
    
    		String objName = TableConst.CUSTOMER;
    		String query = SQLUtil.getCustomerSQL(PortalUtil.getUserId(portletRequest));
    		if (portletId.equals(PortletIDs.CUSTOMER_LIST)) {
    			objName = TableConst.CUSTOMER;
    			query = SQLUtil.getCustomerSQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.CONTACT_LIST)) {
    			objName = TableConst.CONTACT;
    			query = SQLUtil.getContactSQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.MARKET_LIST)) {
    			objName = TableConst.MARKET;
    			query = SQLUtil.getMarketSQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.CLUE_LIST)) {
    			objName = TableConst.CLUE;
    			query = SQLUtil.getClueSQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.ACTIVITY_LIST)) {
    			objName = TableConst.ACTIVITY;
    			query = SQLUtil.getActivitySQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.OPPORTUNITY_LIST)) {
    			objName = TableConst.OPPORTUNITY;
    			query = SQLUtil.getOpportunitySQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.QUOTATION_LIST)) {
    			objName = TableConst.QUOTATION;
    			query = SQLUtil.getQuotationSQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.PRODUCT)) {
    			objName = TableConst.PRODUCT;
    			query = SQLUtil.getProductSQL(companyId);
    		} else if (portletId.equals(PortletIDs.CONTRACT_LIST)) {
    			objName = TableConst.CONTRACT;
    			query = SQLUtil.getContractSQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.ACTIVITY_HISTORY)) {
    			objName = TableConst.ACTIVITY;
    			query = SQLUtil.getActivitySQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.ORDER_LIST)) {
    			objName = TableConst.ORDER;
    			query = SQLUtil.getOrderSQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.RPLAN_LIST)) {
    			objName = TableConst.RPLAN;
    			query = SQLUtil.getRPlanSQL(PortalUtil.getUserId(portletRequest));
    		} else if (portletId.equals(PortletIDs.RRECORD_LIST)) {
    			objName = TableConst.RRECORD;
    			query = SQLUtil.getRRecordSQL(PortalUtil.getUserId(portletRequest));
    		}
    
    		if (view != null) {
    			List<ViewItem> viewItems = ViewItemLocalServiceUtil
    					.searchByViewId(view.getViewId());
    			if (viewItems != null && viewItems.size() > 0) {
    				for (ViewItem viewItem : viewItems) {
    					CompanyColumnDefinition companyColumn = CompanyColumnDefinitionLocalServiceUtil
    							.getCompanyColumnDefinition(viewItem
    									.getColumnDefinitionId());
    					String columnName = companyColumn.getColumnName();
    					String operation = viewItem.getOperator();
    					String queryValue = viewItem.getValue();
    					if (queryValue.equals("customer pond")) {
    						query = "select customer.customerId from CRM_Customer customer where customer.ownerId = 0 and customer.companyId = " + companyId;
    					} else if (queryValue.equals("contact pond")) {
    						query = "select contact.contactId from CRM_Contact contact where contact.ownerId = 0 and contact.companyId = " + companyId;
    					} else {
    						if (!queryValue.equals("own") && companyColumn.getFormType().equals(Constants.FORM_TYPE_PK)) {
    							String searchPkID = SQLUtil.getQueryValue(queryValue, columnName, companyId);
    							if (!operation.equals("ne")) {
    								operation = "eq";
    							}
    
    							query += " and "
    								+ objName
    								+ StringPool.PERIOD
    								+ SQLUtil.filterQuery(columnName)
    								+ SQLUtil.symbolToString(operation, searchPkID);
    
    						} else {
    							query += " and "
    								+ objName
    								+ StringPool.PERIOD
    								+ SQLUtil.filterQuery(columnName)
    								+ SQLUtil.symbolToString(operation, ViewPortlet.handleViewValue(queryValue, userId));
    						}
    					}
    				}
    			}
    		}
    
    		return query;
    	}
    
    	protected String assembledSearchQuery(ActionRequest actionRequest)
    			throws NumberFormatException, PortalException, SystemException {
    		String query = StringPool.BLANK;
    		String portletId = PortalUtil.getPortletId(actionRequest);
    		String objName = PropsUtil.getObjNameByPortletId(portletId);
    		long companyId = PortalUtil.getCompanyId(actionRequest);
    
    		PortletPreferences preferences = actionRequest.getPreferences();
    		String searchColumnsIds = preferences.getValue("search.columns", StringPool.BLANK);
    		if (searchColumnsIds != null && searchColumnsIds.length() > 0) {
    			String[] columnsIdsArray = searchColumnsIds.split(",");
    			for (String columnId : columnsIdsArray) {
    				CompanyColumnDefinition companyColumn = CompanyColumnDefinitionLocalServiceUtil
    						.getCompanyColumnDefinition(Integer.valueOf(columnId));
    
    				String columnName = companyColumn.getColumnName();
    				String formType = companyColumn.getFormType();
    				String searchOperator = ParamUtil.getString(actionRequest, columnName + "Operator");
    				String searchValue = ParamUtil.getString(actionRequest, columnName, StringPool.BLANK);
    
    				if (!searchValue.equals(StringPool.BLANK)) {
    					if (companyColumn.getFormType().equals(Constants.FORM_TYPE_PK)) {
    
    						String searchPkID = SQLUtil.getQueryValue(searchValue, columnName, companyId);
    						if (!searchOperator.equals("ne")) {
    							searchOperator = "eq";
    						}
    
    						query += " and "
    							+ objName
    							+ StringPool.PERIOD
    							+ SQLUtil.filterQuery(columnName)
    							+ SQLUtil.symbolToString(searchOperator, searchPkID);
    					} else {
    						String specialValue = specialColumnName(columnName, searchValue);
    						
    						query += " and "
    							+ objName
    							+ StringPool.PERIOD
    							+ SQLUtil.filterQuery(columnName)
    							+ SQLUtil.symbolToString(searchOperator, specialValue);
    					}
    					actionRequest.setAttribute(columnName + "Operator", searchOperator);
    					actionRequest.setAttribute(columnName, searchValue);
    				} else {
    					if (!searchOperator.equals("none")) {
    						if (formType.equals(Constants.FORM_TYPE_DATE)) {
    							StringBuffer sQuery = new StringBuffer();
    
    							String beginDate = "";
    							String endDate = "";
    
    							String rangeValues = DateUtil.getDateRange(searchOperator);
    							if (rangeValues.length() > 0) {
    								beginDate = rangeValues.split(",")[0];
    								endDate = rangeValues.split(",")[1];
    							}
    							
    							sQuery.append("and");
    							sQuery.append(StringPool.SPACE);
    							sQuery.append(objName);
    							sQuery.append(StringPool.PERIOD);
    							sQuery.append(columnName);
    							sQuery.append(StringPool.SPACE);
    							sQuery.append("between");
    							sQuery.append(StringPool.SPACE);
    							sQuery.append(StringPool.APOSTROPHE);
    							sQuery.append(beginDate + " 00:00:00");
    							sQuery.append(StringPool.APOSTROPHE);
    							sQuery.append(StringPool.SPACE);
    							sQuery.append("and");
    							sQuery.append(StringPool.SPACE);
    							sQuery.append(StringPool.APOSTROPHE);
    							sQuery.append(endDate + " 23:59:59");
    							sQuery.append(StringPool.APOSTROPHE);
    
    							query += sQuery.toString();
    							actionRequest.setAttribute(columnName + "Operator", searchOperator);
    						}
    					}
    				}
    			}
    
    			if (!query.equals(StringPool.BLANK)) {
    				actionRequest.getPortletSession().removeAttribute("pageNo");
    			}
    		}
    		
    		_log.info(query);
    		
    		return query;
    	}
    
    	protected String getSqlQueryForActivity(PortletRequest portletRequest,
    			boolean isHistory, String relation) throws SystemException,
    			PortalException {
    		StringBuffer query = new StringBuffer(StringPool.BLANK);
    		long userId = PortalUtil.getUserId(portletRequest);
    		long companyId = PortalUtil.getCompanyId(portletRequest);
    		query.append(SQLUtil.getActivitySQL(userId))
    			.append(" and activity.companyId = ").append(companyId);
    		long relationObId = ActivityUtils.getRelationOBId(portletRequest,
    				relation);
    		query.append(" and activity.relationObj = ").append(relationObId)
    			.append(" and activity.relation = '").append(relation).append("'");
    		
    		Locale locale = PortalUtil.getCompany(portletRequest).getLocale();
    		String status = LanguageUtil.get(PortletIDs.ACTIVITY_LIST, locale,
    				"has.ended");
    		if (isHistory) {
    			query.append(" and activity.status = '").append(status).append("'");
    		} else {
    			query.append(" and activity.status != '").append(status)
    					.append("'");
    		}
    		query.append(" order by activity.createDate desc");
    		_log.info(query);
    		return query.toString();
    	}
    	
    	protected static void getPrefenceColumn(PortletRequest portletRequest)
    			throws NumberFormatException, PortalException, SystemException {
    		long companyId = PortalUtil.getCompanyId(portletRequest);
    		String portletId = PortalUtil.getPortletId(portletRequest);
    		String tableName = PropsUtil.getTableNameByPortletId(portletId);
    		long userId = PortalUtil.getUserId(portletRequest);
    		View view = null;
    		Cookie viewCookie = CookieUtil.getCookieByName(portletRequest, userId
    				+ "-view-" + tableName);
    		if (viewCookie != null) {
    			String viewIdString = viewCookie.getValue();
    			view = ViewLocalServiceUtil.getView(Long.valueOf(viewIdString));
    		} else {
    			view = ViewLocalServiceUtil.searchByIsDefault(companyId, tableName,
    					true);
    		}
    
    		List<CompanyColumnDefinition> tableHeader = null;
    		if (view != null) {
    			tableHeader = new ArrayList<CompanyColumnDefinition>();
    			List<ViewColumn> viewColumns = ViewColumnLocalServiceUtil
    					.searchByViewId(view.getViewId());
    			if (Validator.isNotNull(viewColumns)) {
    				for (ViewColumn viewColumn : viewColumns) {
    					long companyColumnId = viewColumn.getColumnDefinitionId();
    					CompanyColumnDefinition companyColumn = CompanyColumnDefinitionLocalServiceUtil
    							.getCompanyColumnDefinition(companyColumnId);
    
    					tableHeader.add(companyColumn);
    				}
    			}
    		} else {
    			long groupId = PortalUtil.getScopeGroupId(portletRequest);
    			PortletPreferences preferences = PortletPreferencesUtil
    					.getPortletPreferenceByPortletId(companyId, groupId,
    							portletId);
    			String columnsIds = preferences.getValue("default.display.columns",
    					StringPool.BLANK);
    			if (!columnsIds.equals(StringPool.BLANK)) {
    				String[] columnIdsArray = columnsIds.split(StringPool.COMMA);
    				tableHeader = new ArrayList<CompanyColumnDefinition>();
    				for (int i = 0; i < columnIdsArray.length; i++) {
    					CompanyColumnDefinition companyColumn = CompanyColumnDefinitionLocalServiceUtil
    							.getCompanyColumnDefinition(Long
    									.valueOf(columnIdsArray[i]));
    					tableHeader.add(companyColumn);
    				}
    			}
    		}
    
    		portletRequest.setAttribute("tableHeader", tableHeader);
    	}
    
    	protected static void getDefaultColumn(PortletRequest portletRequest,
    			String portletId) throws PortalException, SystemException {
    		long companyId = PortalUtil.getCompanyId(portletRequest);
    		long groupId = PortalUtil.getScopeGroupId(portletRequest);
    		PortletPreferences preferences = PortletPreferencesUtil
    				.getPortletPreferenceByPortletId(companyId, groupId, portletId);
    		String columnsIds = preferences.getValue("default.display.columns",
    				StringPool.BLANK);
    		List<CompanyColumnDefinition> tableHeader = null;
    		if (!columnsIds.equals(StringPool.BLANK)) {
    			String[] columnIdsArray = columnsIds.split(StringPool.COMMA);
    			tableHeader = new ArrayList<CompanyColumnDefinition>();
    			for (int i = 0; i < columnIdsArray.length; i++) {
    				CompanyColumnDefinition companyColumn = CompanyColumnDefinitionLocalServiceUtil
    						.getCompanyColumnDefinition(Long
    								.valueOf(columnIdsArray[i]));
    				tableHeader.add(companyColumn);
    			}
    		}
    		portletRequest.setAttribute("tableHeader", tableHeader);
    	}
    
    	protected static void getPrefenceColumnByDetail(
    			PortletRequest portletRequest) throws NumberFormatException,
    			PortalException, SystemException {
    		long companyId = PortalUtil.getCompanyId(portletRequest);
    		long groupId = PortalUtil.getScopeGroupId(portletRequest);
    		String portletId = PortalUtil.getPortletId(portletRequest);
    		PortletPreferences preferences = PortletPreferencesUtil
    				.getPortletPreferenceByPortletId(companyId, groupId, portletId);
    
    		List<CompanyColumnDefinition> tableHeader = null;
    
    		String columnsIds = preferences.getValue("default.display.columns",
    				StringPool.BLANK);
    
    		if (!columnsIds.equals(StringPool.BLANK)) {
    			String[] columnIdsArray = columnsIds.split(StringPool.COMMA);
    			tableHeader = new ArrayList<CompanyColumnDefinition>();
    			for (int i = 0; i < columnIdsArray.length; i++) {
    				CompanyColumnDefinition companyColumn = CompanyColumnDefinitionLocalServiceUtil
    						.getCompanyColumnDefinition(Long
    								.valueOf(columnIdsArray[i]));
    				tableHeader.add(companyColumn);
    			}
    		}
    
    		portletRequest.setAttribute("tableHeader", tableHeader);
    	}
    
    	protected static Boolean isExistsPortletInCurrentPage(
    			PortletRequest portletRequest, String portletId)
    			throws PortalException, SystemException {
    		boolean result = false;
    
    		HttpServletRequest request = PortalUtil
    				.getHttpServletRequest(portletRequest);
    		ThemeDisplay themeDisplay = (ThemeDisplay) request
    				.getAttribute(WebKeys.THEME_DISPLAY);
    		String rootPortletId = PortletConstants.getRootPortletId(portletId);
    
    		Layout layout = themeDisplay.getLayout();
    		if (layout != null) {
    			UnicodeProperties typeSettings = layout.getTypeSettingsProperties();
    			for (String key : typeSettings.keySet()) {
    				String value = typeSettings.get(key);
    				int idx = value.indexOf(rootPortletId);
    				if (idx >= 0) {
    					String[] portletIds = StringUtil.split(value);
    					for (String id : portletIds) {
    						if (id.contains(rootPortletId)) {
    							result = true;
    						}
    					}
    				}
    			}
    		} else {
    			_log.debug("Get portlet by portletId not within the current page!");
    		}
    		return result;
    	}
    
    	protected static void clearSession(PortletRequest portletRequest)
    			throws PortalException, SystemException {
    		portletRequest.getPortletSession().removeAttribute("pageNo");
    		if (!isExistsPortletInCurrentPage(portletRequest, PortletIDs.PRODUCT)) {
    			HttpServletRequest request = PortalUtil
    					.getHttpServletRequest(portletRequest);
    			if (request.getSession().getAttribute(
    					"LIFERAY_SHARED_PRODUCT_CATEGORY_ID") != null) {
    				request.getSession().removeAttribute(
    						"LIFERAY_SHARED_PRODUCT_CATEGORY_ID");
    			}
    		}
    	}
    
    	protected static void clearAllSession(PortletRequest portletRequest) {
    
    		HttpServletRequest request = PortalUtil
    				.getHttpServletRequest(portletRequest);
    		if (request.getSession().getAttribute(
    				EntityIdConst.LIFERAY_SHARED_CLUE_ID) != null) {
    			request.getSession().removeAttribute(
    					EntityIdConst.LIFERAY_SHARED_CLUE_ID);
    		}
    		if (request.getSession().getAttribute(
    				EntityIdConst.LIFERAY_SHARED_CONTACT_ID) != null) {
    			request.getSession().removeAttribute(
    					EntityIdConst.LIFERAY_SHARED_CONTACT_ID);
    		}
    		if (request.getSession().getAttribute(
    				EntityIdConst.LIFERAY_SHARED_CONTRACT_ID) != null) {
    			request.getSession().removeAttribute(
    					EntityIdConst.LIFERAY_SHARED_CONTRACT_ID);
    		}
    
    		if (request.getSession().getAttribute(
    				EntityIdConst.LIFERAY_SHARED_CUSTOMER_ID) != null) {
    			request.getSession().removeAttribute(
    					EntityIdConst.LIFERAY_SHARED_CUSTOMER_ID);
    		}
    		if (request.getSession().getAttribute(
    				EntityIdConst.LIFERAY_SHARED_MARKET_ID) != null) {
    			request.getSession().removeAttribute(
    					EntityIdConst.LIFERAY_SHARED_MARKET_ID);
    		}
    		if (request.getSession().getAttribute(
    				EntityIdConst.LIFERAY_SHARED_OPPORTUNITY_ID) != null) {
    			request.getSession().removeAttribute(
    					EntityIdConst.LIFERAY_SHARED_OPPORTUNITY_ID);
    		}
    		if (request.getSession().getAttribute(
    				EntityIdConst.LIFERAY_SHARED_ORDER_ID) != null) {
    			request.getSession().removeAttribute(
    					EntityIdConst.LIFERAY_SHARED_ORDER_ID);
    		}
    		if (request.getSession().getAttribute(
    				EntityIdConst.LIFERAY_SHARED_QUOTATION_ID) != null) {
    			request.getSession().removeAttribute(
    					EntityIdConst.LIFERAY_SHARED_QUOTATION_ID);
    		}
    		if (request.getSession().getAttribute(
    				EntityIdConst.LIFERAY_SHARED_RPLAN_ID) != null) {
    			request.getSession().removeAttribute(
    					EntityIdConst.LIFERAY_SHARED_RPLAN_ID);
    		}
    		if (request.getSession().getAttribute(
    				EntityIdConst.LIFERAY_SHARED_RRECORD_ID) != null) {
    			request.getSession().removeAttribute(
    					EntityIdConst.LIFERAY_SHARED_RRECORD_ID);
    		}
    
    		if (request.getSession().getAttribute("contactLayoutId") != null) {
    			request.getSession().removeAttribute("contactLayoutId");
    		}
    		if (request.getSession().getAttribute("oppLayoutId") != null) {
    			request.getSession().removeAttribute("oppLayoutId");
    		}
    		if (request.getSession().getAttribute("quoLayoutId") != null) {
    			request.getSession().removeAttribute("quoLayoutId");
    		}
    		if (request.getSession().getAttribute("ordLayoutId") != null) {
    			request.getSession().removeAttribute("ordLayoutId");
    		}
    	}
    
    	public void saveNews(ActionRequest actionRequest, ActionResponse actionResponse) {
    
    		Map<String, Object> results = null;
    		PrintWriter out = null;
    		try {
    			results = new HashMap<String, Object>();
    			HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);
    			response.setContentType("text/xml;charset=UTF-8");
    			out = response.getWriter();
    
    			long userId = PortalUtil.getUserId(actionRequest);
    			long companyId = PortalUtil.getCompanyId(actionRequest);
    			Date currentDate = DateUtil.getCurrentLocalDateTime(companyId);
    
    			SocialNews socialNews = null;
    			int type = ParamUtil.getInteger(actionRequest, "type", 0);
    
    			if (type == SocialConst.SOCIAL_NEWS_TYPE_TXT) {
    				actionRequest.setCharacterEncoding("utf-8");
    				String content = ParamUtil.getString(actionRequest, "content");
    				content = java.net.URLDecoder.decode(content, "UTF-8");
    				
    				socialNews = SocialNewsLocalServiceUtil.createSocialNews(IDGenerator.increment(SocialNews.class.getName()));
    				socialNews.setCompanyId(companyId);
    				socialNews.setContent(content);
    				socialNews.setCreateDate(currentDate);
    				socialNews.setOwnerId(userId);
    				socialNews.setModule(ParamUtil.getString(actionRequest, "module"));
    				socialNews.setModuleId(ParamUtil.getLong(actionRequest, "moduleId"));
    				socialNews.setType(type);
    				socialNews = SocialNewsLocalServiceUtil.addSocialNews(socialNews);
    				
    				results.put("news", socialNews);
    				results.put("userName", UserLocalServiceUtil.getUser(userId).getFirstName());
    				results.put("status", "success");
    				
    			} else {
    				ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(), actionRequest);
    				UploadRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
    				uploadRequest.setCharacterEncoding("utf-8");
    				InputStream inputStream = uploadRequest.getFileAsStream("file");
    				String sourceFileName = uploadRequest.getFileName("file");
    				long size = uploadRequest.getSize("file");
    				long groupId = PortalUtil.getScopeGroupId(uploadRequest);
    
    				if (size < 3145728) {
    					long attachmentId = saveFileEntry(companyId, groupId, size, inputStream, sourceFileName, serviceContext);
    
    					String content = ParamUtil.getString(uploadRequest, "content");
    
    					content = java.net.URLDecoder.decode(content, "UTF-8");
    					if (attachmentId > 0) {
    						String fileName = sourceFileName.substring(0, sourceFileName.indexOf("."));
    						if (fileName.length() > 15) {
    							fileName.substring(0, 15);
    						}
    
    						long newsId = IDGenerator.increment(SocialNews.class.getName());
    						socialNews = SocialNewsLocalServiceUtil.createSocialNews(newsId);
    
    						socialNews.setCompanyId(companyId);
    						socialNews.setCreateDate(currentDate);
    						socialNews.setOwnerId(userId);
    						socialNews.setContent(content);
    						socialNews.setModule(ParamUtil.getString(actionRequest, "module"));
    						socialNews.setModuleId(ParamUtil.getLong(actionRequest, "moduleId"));
    						socialNews.setType(type);
    
    						SocialAttachment socialAttachment = SocialAttachmentLocalServiceUtil.createSocialAttachment(IDGenerator.increment(SocialAttachment.class.getName()));
    						socialAttachment.setNewsId(newsId);
    						socialAttachment.setAttachmentId(attachmentId);
    						socialAttachment.setType(type);
    						if (type == SocialConst.SOCIAL_ATTACHMENT_TYPE_IMG) {
    							socialAttachment.setAttachmentComments(fileName);
    						}
    						SocialAttachmentLocalServiceUtil.addSocialAttachment(socialAttachment);
    						socialNews = SocialNewsLocalServiceUtil.addSocialNews(socialNews);
    
    						ThemeDisplay themeDisplay = (ThemeDisplay) uploadRequest.getAttribute(WebKeys.THEME_DISPLAY);
    						String previewFileURL = LiferayUserUtil.getPhotoPath(attachmentId, themeDisplay);
    						results.put("userAvatar", previewFileURL);
    						results.put("fileName", fileName);
    						results.put("fileSize", "下载 " + sourceFileName.substring(sourceFileName.indexOf(".") + 1) + " ( " + TextUtil.convertFileSize(size)+ " ) ");
    
    						results.put("news", socialNews);
    						results.put("userName", UserLocalServiceUtil.getUser(userId).getFirstName());
    						results.put("status", "success");
    					}
    				} else {
    					results.put("status", "size_error");
    				}
    			}
    			
    			JSONObject jObject = new JSONObject(results);
    			out.print(jObject);
    		} catch (FileSizeException e) {
    			results.put("status", "size");
    			_log.error(e);
    		} catch (SystemException e) {
    			results.put("status", "fail");
    			_log.error(e);
    		} catch (IOException e) {
    			results.put("status", "fail");
    			_log.error(e);
    		} catch (PortalException e) {
    			results.put("status", "fail");
    			_log.error(e);
    		} catch (Exception e) {
    			results.put("status", "fail");
    			_log.error(e);
    		} finally {
    			out.flush();
    			out.close();
    		}
    	}
    
    	public void removeNews(ActionRequest actionRequest, ActionResponse actionResponse) {
    		PrintWriter out = null;
    		try {
    			HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);
    			out = response.getWriter();
    			long newsId = ParamUtil.getLong(actionRequest, "newsId" , 0l);
    
    			if (newsId > 0) {
    				List<SocialComments> socialComments = SocialCommentsLocalServiceUtil.searchByNewsId(newsId);
    				if (Validator.isNotNull(socialComments)) {
    					for (int i = 0; i < socialComments.size(); i++) {
    						SocialCommentsLocalServiceUtil.deleteSocialComments(socialComments.get(i));
    					}
    				}
    
    				List<SocialAttachment> socialAttachments = SocialAttachmentLocalServiceUtil.searchByNewsId(newsId);
    				if (Validator.isNotNull(socialAttachments)) {
    					for (SocialAttachment attachment : socialAttachments) {
    						long attachmentId = attachment.getAttachmentId();
    						if (attachmentId > 0) {
    							DLFileEntryLocalServiceUtil.deleteDLFileEntry(attachmentId);
    						}
    						SocialAttachmentLocalServiceUtil.deleteSocialAttachment(attachment.getSocialAttachmentId());
    					}
    				}
    				
    				SocialNewsLocalServiceUtil.deleteSocialNews(newsId);
    			}
    			out.print("success");
    		} catch (PortalException e) {
    			out.print("fail");
    			_log.error(e);
    		} catch (SystemException e) {
    			out.print("fail");
    			_log.error(e);
    		} catch (IOException e) {
    			out.print("fail");
    			_log.error(e);
    		} finally {
    			out.flush();
    			out.close();
    		}
    	}
    
    	public void saveComments(ActionRequest actionRequest, ActionResponse actionResponse) {
    		Map<String, Object> results = null;
    		PrintWriter out = null;
    		try {
    			results = new HashMap<String, Object>();
    			HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);
    			response.setContentType("text/xml;charset=UTF-8"); 
    			out = response.getWriter();
    
    			long newsId = ParamUtil.getLong(actionRequest, "newsId" , 0l);
    
    			if (newsId > 0) {
    				int type = ParamUtil.getInteger(actionRequest, "type", 0);
    				long userId = PortalUtil.getUserId(actionRequest);
    				long companyId = PortalUtil.getCompanyId(actionRequest);
    				Date currentDate = DateUtil.getCurrentLocalDateTime(companyId);
    				
    				//String content = new String(ParamUtil.getString(actionRequest, "content").getBytes("iso8859-1"), "utf-8");
    				actionRequest.setCharacterEncoding("utf-8");
    				String content = ParamUtil.getString(actionRequest, "content");
    				content = java.net.URLDecoder.decode(content, "UTF-8");
    				
    				SocialComments socialComments = SocialCommentsLocalServiceUtil
    					.createSocialComments(IDGenerator.increment(SocialComments.class.getName()));
    				socialComments.setCreateDate(currentDate);
    				socialComments.setCommenterId(userId);
    				socialComments.setNewsId(newsId);
    				socialComments.setContent(content);
    				socialComments.setType(type);
    
    				socialComments = SocialCommentsLocalServiceUtil.addSocialComments(socialComments);
    
    				results.put("commentId", socialComments.getCommentId());
    				results.put("content", socialComments.getContent());
    				results.put("createDate", new PrettyDateFormat("## a HH:mm", "yy-MM-dd a HH:mm").format(currentDate));
    				results.put("userName", UserLocalServiceUtil.getUser(userId).getFirstName());
    
    				if (type == 1) {
    					String userNames = LiferayUserUtil.getUserNames(
    							SocialCommentsLocalServiceUtil
    									.searchILikeByNewsId(newsId), PortalUtil
    									.getUserId(actionRequest));
    					results.put("userNames", userNames);
    				}
    				results.put("status", "success");
    				JSONObject jObject = new JSONObject(results);
    				out.print(jObject);
    			}
    		} catch (SystemException e) {
    			results.put("status", "fail");
    			_log.error(e);
    		} catch (IOException e) {
    			results.put("status", "fail");
    			_log.error(e);
    		} catch (PortalException e) {
    			results.put("status", "fail");
    			_log.error(e);
    		} finally {
    			out.flush();
    			out.close();
    		}
    	}
    
    	public void removeComments(ActionRequest actionRequest, ActionResponse actionResponse) {
    		PrintWriter out = null;
    		try {
    			HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse);
    			out = response.getWriter();
    			long commentsId = ParamUtil.getLong(actionRequest, "commentsId" , 0l);
    			SocialComments socialComment = SocialCommentsLocalServiceUtil.getSocialComments(commentsId);
    			long newsId = socialComment.getNewsId();
    			if (commentsId > 0) {
    				SocialCommentsLocalServiceUtil.deleteSocialComments(commentsId);
    			}
    			
    			if (ParamUtil.getInteger(actionRequest, "type", 0) == 1) {
    				String userNames = LiferayUserUtil.getUserNames(
    						SocialCommentsLocalServiceUtil
    								.searchILikeByNewsId(newsId), PortalUtil
    								.getUserId(actionRequest));
    				out.print(userNames);
    			} else {
    				out.print("success");
    			}
    			
    		} catch (PortalException e) {
    			out.print("fail");
    			_log.error(e);
    		} catch (SystemException e) {
    			out.print("fail");
    			_log.error(e);
    		} catch (IOException e) {
    			out.print("fail");
    			_log.error(e);
    		} finally {
    			out.flush();
    			out.close();
    		}
    	}
    
    	private long saveFileEntry(long companyId, long groupId, long size,
    			InputStream inputStream, String sourceFileName,
    			ServiceContext serviceContext) throws Exception  {
    
    		long folderId = 0;
    		List<DLFolder> dlFolders = DLFolderLocalServiceUtil.getCompanyFolders(companyId, -1, -1);
    		if (Validator.isNotNull(dlFolders)) {
    			for (DLFolder dlFolder : dlFolders) {
    				if (dlFolder.getName().equals("Social Image")) {
    					folderId = dlFolder.getFolderId();
    				}
    			}
    		}
    
    		if (folderId == 0) {
    			folderId = updateFolder(companyId, groupId, serviceContext);
    		}
    
    		long repositoryId = groupId;
    		String title = TextUtil.getRandomString(8);
    		String description = "Avatar";
    		String changeLog = StringPool.BLANK;
    		String contentType = MimeTypesUtil.getContentType(title);
    
    		// Add file entry
    
    		FileEntry fileEntry = DLAppServiceUtil.addFileEntry(
    			repositoryId, folderId, sourceFileName, contentType, title,
    			description, changeLog, inputStream, size, serviceContext);
    
    		long guestRoleId = com.liferay.portal.service.RoleLocalServiceUtil.getRole(companyId, RoleConstants.GUEST).getRoleId();
    		ResourcePermissionLocalServiceUtil.setResourcePermissions(companyId, DLFileEntry.class.getName(), 4, String.valueOf(fileEntry.getFileEntryId()), guestRoleId, new String[] {ActionKeys.VIEW});
    
    		return fileEntry.getFileEntryId();
    	}
    
    	private long updateFolder(long companyId, long groupId,
    			ServiceContext serviceContext) throws Exception {
    		long parentFolderId = 0;
    		long repositoryId = groupId;
    		String folderName = "Social Image";
    		String description = folderName;
    
    		// Add folder
    		Folder folder = DLAppServiceUtil.addFolder(repositoryId,
    				parentFolderId, folderName, description, serviceContext);
    
    		long guestRoleId = com.liferay.portal.service.RoleLocalServiceUtil
    				.getRole(companyId, RoleConstants.GUEST).getRoleId();
    		
    		ResourcePermissionLocalServiceUtil.setResourcePermissions(companyId,
    				DLFolder.class.getName(), 4,
    				String.valueOf(folder.getFolderId()), guestRoleId,
    				new String[] { ActionKeys.VIEW });
    
    		return folder.getFolderId();
    	}
    
    	private String specialColumnName(String columnName, String searchValue) {
    		
    		if (columnName.equals("auditStatus")) {
    			if (searchValue.equals("通过")) {
    				searchValue = "pass";
    			} else if (searchValue.equals("未通过")) {
    				searchValue = "refuse";
    			} else if (searchValue.equals("待申请")) {
    				searchValue = "request";
    			} else if (searchValue.equals("审核中")) {
    				searchValue = "audit";
    			}
    		}
    		return searchValue;
    	}
    
    	protected String editJSP;
    	protected String viewJSP;
    	protected String helpJSP;
    
    	protected final static String NOT_OPERATOR_JSP = "/jsp/not-operator.jsp";
    	protected final static String NEED_LOGIN_JSP = "/jsp/need-login.jsp";
    
    	private static Log _log = LogFactoryUtil.getLog(BasePortlet.class);
    
    }
    

      

  • 相关阅读:
    ireport +jasperreport 中文不能显示
    ireport +jasperreport 中文不能显示
    JDBC的批量处理语句
    tattoo实现adhoc连接
    tattoo实现adhoc连接
    网络突然掉线或者不小心putty被关掉等等原因 造成安装过程被中断怎么办?
    网络突然掉线或者不小心putty被关掉等等原因 造成安装过程被中断怎么办?
    Linux SSH命令大全,新手必看SSH命令
    修改SSH端口和修改vsftpd端口更安全
    Linux SSH命令大全,新手必看SSH命令
  • 原文地址:https://www.cnblogs.com/airycode/p/4810253.html
Copyright © 2020-2023  润新知