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); }
liferay项目经验之BasePortlet的更多相关文章
- 《项目经验》--通过js获取前台数据向一般处理程序传递Json数据,并解析Json数据,将前台传来的Json数据写入数据库表中
先看一下我要实现的功能界面: 这个界面的功能在图中已有展现,课程分配(教师教授哪门课程)在之前的页面中已做好.这个页面主要实现的是授课,即给老师教授的课程分配学生.此页面实现功能的步骤已在页面 ...
- Java项目经验——程序员成长的关键(转载)
Java就是用来做项目的!Java的主要应用领域就是企业级的项目开发!要想从事企业级的项目开发,你必须掌握如下要点:1.掌握项目开发的基本步骤2.具备极强的面向对象的分析与设计技巧3.掌握用例驱动.以 ...
- Java项目经验
Java项目经验 转自CSDN. Java就是用来做项目的!Java的主要应用领域就是企业级的项目开发!要想从事企业级的项目开发,你必须掌握如下要点:1.掌握项目开发的基本步骤2.具备极强的面向对象的 ...
- OSG项目经验2<在场景中添加文字面版>
添加文字版需要用到osg的三个名字空间: osgText::Text,这个类用来添加文字和设置文字的一些属性: ...
- 最近面试java后端开发的感受:如果就以平时项目经验来面试,通过估计很难——再论面试前的准备
在上周,我密集面试了若干位Java后端的候选人,工作经验在3到5年间.我的标准其实不复杂:第一能干活,第二Java基础要好,第三最好熟悉些分布式框架,我相信其它公司招初级开发时,应该也照着这个标准来面 ...
- java程序员面试交流项目经验
粘贴自:https://blog.csdn.net/wangyuxuan_java/article/details/8778211 1:请你介绍一下你自己 这是面试官常问的问题.一般人回答这个问题过于 ...
- 项目经验分享[转自min.jiang]
最近三个月,我非常荣幸的做为TeamLeader带领几个小组成员做了一个国外项目,这里想为大家分享一些小经验,尽管我佣有六年多的项目经验,但我一直的方向是架构师.大家知道架构师一般情况是偏向技 ...
- Georgia Tech Online Master of Science in Computer Science 项目经验分享
Georgia Tech Online Master of Science in Computer Science 项目经验分享 Posted on 2014/04/22 项目关键词:工科名校,计算机 ...
- IdentityServer4系列之中文文档及实际项目经验分享
0.前言 原文:http://docs.identityserver.io/en/release/声明: 1.目录一至五章节根据IdentityServer英文文档翻译而来,有些内容会根据自己的理解来 ...
随机推荐
- Google APK下载
在线下载google play中apk的网站 1.http://apps.evozi.com/apk-downloader 2.http://downloader-apk.com/ 3.http:// ...
- gulp生成发布包脚本
var formPost = require('./tools/submit.js');var gulp = require('gulp'), zip = require('gulp-zip'), h ...
- [转]OpenStack Neutron解析
1.为什么还需要linux bridge的部署方式? 2.哪一个网桥起着交换机的作用? 3.neutron如何实现私有网络的隔离 =================================== ...
- jenkins与SonarQube集成
一.SonarQube 我的理解是,SonarQube就是一个对代码进行分析的平台,其功能可以通过插件扩展.支持多种语言,也支持静态代码检查.发现潜在bug等. 以下是参考信息: 维基百科:https ...
- 兵器簿之github的配置和使用
1.注册一个github 账号,这个大家都懂得了啊 2.配置 (1 检查:进入终端,在用户目录下输入: ls -al ~/.ssh 得到下图代表本地没有配置过github 过. (2 创建一个目录,输 ...
- ftok函数
ftok函数 系统建立IPC通讯(消息队列.信号量和共享内存)时必须指定一个ID值.通常情况下,该id值通过ftok函数得到. ftok原型 头文件: #include <sys/types.h ...
- Java基础之理解封装,继承,多态三大特性
目录 封装 继承 多态 封装 封装隐藏了类的内部实现机制,可以在不影响使用的情况下改变类的内部结构,同时也保护了数据.对外界而已它的内部细节是隐藏的,暴露给外界的只是它的访问方法. 代码理解 publ ...
- 基本类型互相之间转化可以用Covent类来实现。
一.C#类型的转换 在c#中类型的转换分两种:显式和隐式,基本的规则如下: 1.基类对象转化为子类对象,必须显式转换,规则:(类型名) 对象.2.值类型和引用类型的转换采用装箱(boxing)或拆箱( ...
- hihocoder 1284 - 机会渺茫
N有N_cnt个约数,M有M_cnt个约数,那么总共有N_cnt * M_cnt种对应情况. 假设其中有D_cnt个对应结果是相等的,而这D_cnt个数正好是gcd(N,M)的所有约数. 例如: N= ...
- Python:正则表达式概念
#正则表达式内容非常多,网上的学习资源也是目不暇接,我从中筛选学习并且整理出以下 的学习笔记 一.正则表达式匹配过程: 1.依次拿出表达式和文本中的字符比较 2.如果每一个字符都能匹配,则匹配成功:一 ...