Migrate ALL java files from /src to /src/main/java - OFBIZ-7790

This is the first of two steps in the above mentioned JIRA. This
first step changes the java source directory for every component
from /src to /src/main/java. The next step will be adding unit
tests to every component in /src/test/java

Thank you to Deepak Dixit for tips on how to use the SVN commands
to make the appropriate file moving.


git-svn-id: https://svn.apache.org/repos/asf/ofbiz/trunk@1752838 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Taher A. Alkhateeb
2016-07-15 14:17:14 +00:00
parent 67a988ab0e
commit b37ef2d280
1244 changed files with 2 additions and 2 deletions
@@ -0,0 +1,243 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
import java.applet.Applet;
import java.applet.AppletContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.ofbiz.base.util.UtilValidate;
/**
* Control Applet - Client applet for page pushing and (future) chat
*/
@SuppressWarnings("serial")
public class ControlApplet extends Applet implements Runnable {
private static String pushUrl = "/commonapp/control/pushapplet";
private static String pullUrl = "/commonapp/control/pullapplet";
protected AppletContext ctx = null;
protected String sessionId = null;
protected String visitId = null;
protected String serverUrl = null;
protected String timeoutUrl = null;
protected String currentPage = null;
protected String debug = null;
protected int waitTime = 1500;
protected int timeout = 300000;
protected boolean isRunning = false;
protected boolean stopped = true;
protected Thread thread = null;
@Override
public void init() {
ctx = this.getAppletContext();
this.sessionId = this.getParameter("sessionId");
this.visitId = this.getParameter("visitId");
this.serverUrl = this.getParameter("serverUrl");
this.timeoutUrl = this.getParameter("timeoutUrl");
this.currentPage = this.getParameter("currentPage");
this.debug = this.getParameter("debug");
// see if we override the integer values
try {
int waitInt = Integer.parseInt(this.getParameter("waitTime"));
if (waitInt > 0)
waitTime = waitInt;
} catch (NumberFormatException e) {
}
try {
int outInt = Integer.parseInt(this.getParameter("timeout"));
if (outInt > 0)
timeout = outInt;
} catch (NumberFormatException e) {
}
if (serverUrl != null) {
boolean sessionOkay = false;
boolean visitOkay = false;
boolean pageOkay = false;
if (UtilValidate.isNotEmpty(sessionId))
sessionOkay = true;
if (UtilValidate.isNotEmpty(visitId))
visitOkay = true;
if (UtilValidate.isNotEmpty(currentPage))
pageOkay = true;
if (sessionOkay && visitOkay && pageOkay) {
// tell the host about our current page (mainly for followers)
this.push();
}
// start the polling thread
this.isRunning = true;
this.stopped = false;
thread = new Thread(this);
thread.setDaemon(false);
thread.start();
}
}
@Override
public void destroy() {
this.stopped = true;
}
// poll the servlet for page request
public void run() {
while (isRunning && !stopped) {
this.pull();
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
this.stopped = true;
this.isRunning = false;
}
}
if (debug != null && debug.equalsIgnoreCase("true"))
System.out.println("Polling finished.");
}
protected void pull() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("sessionId", this.sessionId.trim());
params.put("visitId", this.visitId.trim());
String pullResp = null;
URL callPullUrl = null;
try {
callPullUrl = new URL(serverUrl + pullUrl);
} catch (MalformedURLException e) {
}
if (callPullUrl != null) {
try {
pullResp = callServer(callPullUrl, params);
} catch (IOException e) {
}
}
if (UtilValidate.isNotEmpty(pullResp)) {
URL docUrl = null;
try {
docUrl = new URL(pullResp);
} catch (MalformedURLException e) {
}
if (docUrl != null)
ctx.showDocument(docUrl, "appletWindow");
}
}
protected void push() {
Map<String, Object> params = new HashMap<String, Object>();
params.put("sessionId", this.sessionId.trim());
params.put("visitId", this.visitId.trim());
params.put("currentPage", this.currentPage.trim());
URL callPushUrl = null;
try {
callPushUrl = new URL(serverUrl + pushUrl);
} catch (MalformedURLException e) {
}
if (callPushUrl != null) {
try {
callServer(callPushUrl, params);
} catch (IOException e) {
}
}
}
private String callServer(URL serverUrl, Map<String, Object> parms) throws IOException {
// send the request
String parameters = this.encodeArgs(parms);
if (debug != null && debug.equalsIgnoreCase("true")) {
System.out.println("Sending parameters: " + parameters);
}
URLConnection uc = serverUrl.openConnection();
uc.setDoOutput(true);
uc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
PrintWriter pw = new PrintWriter(uc.getOutputStream());
pw.println(parameters);
pw.close();
// read the response
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String responseStr = in.readLine();
in.close();
if (responseStr != null) {
responseStr = responseStr.trim();
}
if (debug != null && debug.equalsIgnoreCase("true")) {
System.out.println("Receive response: " + responseStr);
}
return responseStr;
}
public String encodeArgs(Map<String, Object> args) {
StringBuffer buf = new StringBuffer();
if (args != null) {
Set<Map.Entry<String, Object>> entrySet = args.entrySet();
for (Map.Entry<String, Object> entry : entrySet) {
String name = entry.getKey();
Object value = entry.getValue();
String valueStr = null;
if (name != null && value != null) {
if (value instanceof String) {
valueStr = (String) value;
} else {
valueStr = value.toString();
}
if (UtilValidate.isNotEmpty(valueStr)) {
if (buf.length() > 0) buf.append('&');
try {
buf.append(URLEncoder.encode(name, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
buf.append('=');
try {
buf.append(URLEncoder.encode(valueStr, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
}
return buf.toString();
}
}
@@ -0,0 +1,340 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.security.Security;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.webapp.website.WebSiteWorker;
/**
* ContentManagementEvents Class
*/
public class ContentManagementEvents {
public static final String module = ContentManagementEvents.class.getName();
public static String updateStaticValues(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
Security security = (Security)request.getAttribute("security");
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
ServletContext servletContext = session.getServletContext();
String webSiteId = WebSiteWorker.getWebSiteId(request);
Delegator delegator = (Delegator)request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher)request.getAttribute("dispatcher");
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
//if (Debug.infoOn()) Debug.logInfo("in updateStaticValues, paramMap:" + paramMap , module);
String parentPlaceholderId = (String)paramMap.get("ph");
if (UtilValidate.isEmpty(parentPlaceholderId)) {
request.setAttribute("_ERROR_MESSAGE_", "ParentPlaceholder is empty.");
return "error";
}
List<GenericValue> allPublishPointList = null;
List<String []> permittedPublishPointList = null;
List<Map<String, Object>> valueList = null;
try {
allPublishPointList = ContentManagementWorker.getAllPublishPoints(delegator, webSiteId);
permittedPublishPointList = ContentManagementWorker.getPermittedPublishPoints(delegator, allPublishPointList, userLogin, security, "_ADMIN", null, null);
valueList = ContentManagementWorker.getStaticValues(delegator, parentPlaceholderId, permittedPublishPointList);
} catch (GeneralException e) {
Debug.logError(e.getMessage(), module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
/*
Set keySet = paramMap.keySet();
Iterator itKeySet = keySet.iterator();
Map contentIdLookup = new HashMap<String, Object>();
while (itKeySet.hasNext()) {
String idxAndContentId = (String)itKeySet.next();
int pos = idxAndContentId.indexOf("_");
if (pos > 0) {
String idxStr = idxAndContentId.substring(0, pos);
int idx = Integer.parseInt(idxStr);
String contentId = idxAndContentId.substring(pos + 1);
contentIdLookup.put(contentId, Integer.valueOf(idx));
}
}
*/
int counter = 0;
for (Map<String, Object> map : valueList) {
String contentId = (String)map.get("contentId");
//Integer idxObj = (Integer)contentIdLookup.get(contentId);
//int idx = idxObj.intValue();
for (String [] pubArr : permittedPublishPointList) {
String pubContentId = pubArr[0];
String pubValue = (String)map.get(pubContentId);
String paramName = Integer.toString(counter) + "_" + pubContentId;
String paramValue = (String)paramMap.get(paramName);
//if (Debug.infoOn()) Debug.logInfo("in updateStaticValues, contentId:" + contentId + " pubContentId:" + pubContentId + " pubValue:" + pubValue + " paramName:" + paramName + " paramValue:" + paramValue, module);
Map<String, Object> serviceIn = new HashMap<String, Object>();
serviceIn.put("userLogin", userLogin);
serviceIn.put("contentIdTo", contentId);
serviceIn.put("contentId", pubContentId);
serviceIn.put("contentAssocTypeId", "SUBSITE");
try {
if (UtilValidate.isNotEmpty(paramValue)) {
if (!paramValue.equals(pubValue)) {
if (paramValue.equalsIgnoreCase("Y")) {
serviceIn.put("fromDate", UtilDateTime.nowTimestamp());
dispatcher.runSync("createContentAssoc", serviceIn);
} else if (paramValue.equalsIgnoreCase("N") && pubValue.equalsIgnoreCase("Y")) {
serviceIn.put("thruDate", UtilDateTime.nowTimestamp());
Timestamp fromDate = (Timestamp)map.get(pubContentId + "FromDate");
serviceIn.put("fromDate", fromDate);
dispatcher.runSync("updateContentAssoc", serviceIn);
}
}
} else if (UtilValidate.isNotEmpty(pubValue)) {
if (pubValue.equalsIgnoreCase("Y")) {
serviceIn.put("thruDate", UtilDateTime.nowTimestamp());
Timestamp fromDate = (Timestamp)map.get(pubContentId + "FromDate");
serviceIn.put("fromDate", fromDate);
dispatcher.runSync("updateContentAssoc", serviceIn);
}
}
} catch (GenericServiceException e) {
Debug.logError(e.getMessage(), module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
}
counter++;
}
return "success";
}
public static String createStaticValue(HttpServletRequest request, HttpServletResponse response) {
String retValue = "success";
return retValue;
}
public static String updatePublishLinks(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
Security security = (Security)request.getAttribute("security");
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
ServletContext servletContext = session.getServletContext();
String webSiteId = WebSiteWorker.getWebSiteId(request);
Delegator delegator = (Delegator)request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher)request.getAttribute("dispatcher");
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, paramMap:" + paramMap , module);
String targContentId = (String)paramMap.get("contentId"); // The content to be linked to one or more sites
String roles = null;
String authorId = null;
GenericValue authorContent = ContentManagementWorker.getAuthorContent(delegator, targContentId);
if (authorContent != null) {
authorId = authorContent.getString("contentId");
} else {
request.setAttribute("_ERROR_MESSAGE_", "authorContent is empty.");
return "error";
}
// Determine if user is owner of target content
String userLoginId = userLogin.getString("userLoginId");
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, userLoginId:" + userLoginId + " authorId:" + authorId , module);
List<String> roleTypeList = null;
if (authorId != null && userLoginId != null && authorId.equals(userLoginId)) {
roles = "OWNER";
roleTypeList = StringUtil.split(roles, "|");
}
List<String> targetOperationList = UtilMisc.<String>toList("CONTENT_PUBLISH");
List<String> contentPurposeList = null; //UtilMisc.toList("ARTICLE");
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, roles:" + roles +" roleTypeList:" + roleTypeList , module);
String permittedAction = (String)paramMap.get("permittedAction"); // The content to be linked to one or more sites
String permittedOperations = (String)paramMap.get("permittedOperations"); // The content to be linked to one or more sites
if (UtilValidate.isEmpty(targContentId)) {
request.setAttribute("_ERROR_MESSAGE_", "targContentId is empty.");
return "error";
}
// Get all the subSites that the user is permitted to link to
List<Object []> origPublishedLinkList = null;
try {
// TODO: this needs to be given author userLogin
EntityQuery.use(delegator).from("UserLogin").where("userLoginId", authorId).cache().queryOne();
origPublishedLinkList = ContentManagementWorker.getPublishedLinks(delegator, targContentId, webSiteId, userLogin, security, permittedAction, permittedOperations, roles);
} catch (GenericEntityException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
} catch (GeneralException e2) {
request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
return "error";
}
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, origPublishedLinkList:" + origPublishedLinkList , module);
// make a map of the values that are passed in using the top subSite as the key.
// Content can only be linked to one subsite under a top site (ends with "_MASTER")
Map<String, String> siteIdLookup = new HashMap<String, String>();
for (String param : paramMap.keySet()) {
int pos = param.indexOf("select_");
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, param:" + param + " pos:" + pos , module);
if (pos >= 0) {
String siteId = param.substring(7);
String subSiteVal = (String)paramMap.get(param);
siteIdLookup.put(siteId, subSiteVal);
}
}
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, siteIdLookup:" + siteIdLookup , module);
// Loop thru all the possible subsites
Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
// int counter = 0;
String responseMessage = null;
String errorMessage = null;
// String permissionMessage = null;
boolean statusIdUpdated = false;
Map<String, Object> results = null;
for (Object [] arr : origPublishedLinkList) {
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, arr:" + Arrays.asList(arr) , module);
String contentId = (String)arr[0]; // main (2nd level) site id
String origSubContentId = null;
List<Object []> origSubList = UtilGenerics.checkList(arr[1]);
// Timestamp topFromDate = (Timestamp)arr[3];
Timestamp origFromDate = null;
for (Object [] pubArr : origSubList) {
// see if a link already exists by looking for non-null fromDate
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, pubArr:" + Arrays.asList(pubArr) , module);
Timestamp fromDate = (Timestamp)pubArr[2];
origSubContentId = null;
if (fromDate != null) {
origSubContentId = (String)pubArr[0];
origFromDate = fromDate;
break;
}
}
String currentSubContentId = siteIdLookup.get(contentId);
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, currentSubContentId:" + currentSubContentId , module);
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, origSubContentId:" + origSubContentId , module);
try {
if (UtilValidate.isNotEmpty(currentSubContentId)) {
if (!currentSubContentId.equals(origSubContentId)) {
// disable existing link
if (UtilValidate.isNotEmpty(origSubContentId) && origFromDate != null) {
List<GenericValue> oldActiveValues = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", targContentId,
"contentIdTo", origSubContentId,
"contentAssocTypeId", "PUBLISH_LINK",
"thruDate", null)
.queryList();
for (GenericValue cAssoc : oldActiveValues) {
cAssoc.set("thruDate", nowTimestamp);
cAssoc.store();
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, deactivating:" + cAssoc , module);
}
}
// create new link
Map<String, Object> serviceIn = new HashMap<String, Object>();
serviceIn.put("userLogin", userLogin);
serviceIn.put("contentId", targContentId);
serviceIn.put("contentAssocTypeId", "PUBLISH_LINK");
serviceIn.put("fromDate", nowTimestamp);
serviceIn.put("contentIdTo", currentSubContentId);
serviceIn.put("roleTypeList", roleTypeList);
serviceIn.put("targetOperationList", targetOperationList);
serviceIn.put("contentPurposeList", contentPurposeList);
results = dispatcher.runSync("createContentAssoc", serviceIn);
responseMessage = (String)results.get(ModelService.RESPONSE_MESSAGE);
if (UtilValidate.isNotEmpty(responseMessage)) {
errorMessage = (String)results.get(ModelService.ERROR_MESSAGE);
Debug.logError("in updatePublishLinks, serviceIn:" + serviceIn , module);
Debug.logError(errorMessage, module);
request.setAttribute("_ERROR_MESSAGE_", errorMessage);
return "error";
}
serviceIn = new HashMap<String, Object>();
serviceIn.put("userLogin", userLogin);
serviceIn.put("contentId", targContentId);
serviceIn.put("contentAssocTypeId", "PUBLISH_LINK");
serviceIn.put("fromDate", nowTimestamp);
serviceIn.put("contentIdTo", contentId);
serviceIn.put("roleTypeList", roleTypeList);
serviceIn.put("targetOperationList", targetOperationList);
serviceIn.put("contentPurposeList", contentPurposeList);
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, serviceIn(3b):" + serviceIn , module);
results = dispatcher.runSync("createContentAssoc", serviceIn);
//if (Debug.infoOn()) Debug.logInfo("in updatePublishLinks, results(3b):" + results , module);
if (!statusIdUpdated) {
try {
GenericValue targContent = EntityQuery.use(delegator).from("Content").where("contentId", targContentId).queryOne();
targContent.set("statusId", "CTNT_PUBLISHED");
targContent.store();
statusIdUpdated = true;
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
}
}
} else if (UtilValidate.isNotEmpty(origSubContentId)) {
// if no current link is passed in, look to see if there is an existing link(s) that must be disabled
List<GenericValue> oldActiveValues = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", targContentId,
"contentIdTo", origSubContentId,
"contentAssocTypeId", "PUBLISH_LINK",
"thruDate", null)
.queryList();
for (GenericValue cAssoc : oldActiveValues) {
cAssoc.set("thruDate", nowTimestamp);
cAssoc.store();
}
}
} catch (GenericEntityException e) {
Debug.logError(e.getMessage(), module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
} catch (GenericServiceException e2) {
Debug.logError(e2, module);
request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
return "error";
}
}
return "success";
}
}
@@ -0,0 +1,709 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.collections.LifoSet;
import org.ofbiz.content.content.ContentServicesComplex;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntity;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericPK;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.entityext.permission.EntityPermissionChecker;
import org.ofbiz.minilang.MiniLangException;
import org.ofbiz.security.Security;
/**
* ContentManagementWorker Class
*/
public final class ContentManagementWorker {
public static final String module = ContentManagementWorker.class.getName();
private static Map<String, GenericValue> cachedWebSitePublishPoints = new HashMap<String, GenericValue>();
private static Map<String, Map<String, Object>> cachedStaticValues = new HashMap<String, Map<String,Object>>();
private ContentManagementWorker() {}
public static void mruAdd(HttpServletRequest request, GenericEntity pk, String suffix) {
HttpSession session = request.getSession();
mruAdd(session, pk);
}
public static void mruAdd(HttpServletRequest request, GenericEntity pk) {
HttpSession session = request.getSession();
mruAdd(session, pk);
}
public static void mruAdd(HttpSession session, GenericEntity pk) {
if (pk == null) {
return;
}
Map<String, LifoSet<Object>> lookupCaches = UtilGenerics.checkMap(session.getAttribute("lookupCaches"));
if (lookupCaches == null) {
lookupCaches = new HashMap<String, LifoSet<Object>>();
session.setAttribute("lookupCaches", lookupCaches);
}
String entityName = pk.getEntityName();
mruAddByEntityName(entityName, pk, lookupCaches);
}
/**
* Makes an entry in the "most recently used" cache. It picks the cache
* by the entity name and builds a signature from the primary key values.
*
* @param entityName
* @param lookupCaches
* @param pk either a GenericValue or GenericPK - populated
*/
public static void mruAddByEntityName(String entityName, GenericEntity pk, Map<String, LifoSet<Object>> lookupCaches) {
String cacheEntityName = entityName;
LifoSet<Object> lkupCache = lookupCaches.get(cacheEntityName);
if (lkupCache == null) {
lkupCache = new LifoSet<Object>();
lookupCaches.put(cacheEntityName, lkupCache);
}
lkupCache.add(pk.getPrimaryKey());
if (Debug.infoOn()) Debug.logInfo("in mruAddByEntityName, entityName:" + entityName + " lifoSet.size()" + lkupCache.size(), module);
}
public static Iterator<Object> mostRecentlyViewedIterator(String entityName, Map<String, LifoSet<Object>> lookupCaches) {
String cacheEntityName = entityName;
LifoSet<Object> lkupCache = lookupCaches.get(cacheEntityName);
if (lkupCache == null) {
lkupCache = new LifoSet<Object>();
lookupCaches.put(cacheEntityName, lkupCache);
}
Iterator<Object> mrvIterator = lkupCache.iterator();
return mrvIterator;
}
/**
* Builds a string signature from a GenericValue or GenericPK.
*
* @param pk either a populated GenericValue or GenericPK.
* @param suffix a string that can be used to distinguish the signature (probably not used).
*/
public static String buildPKSig(GenericEntity pk, String suffix) {
StringBuilder sig = new StringBuilder("");
Collection<String> keyColl = pk.getPrimaryKey().getAllKeys();
List<String> keyList = UtilMisc.makeListWritable(keyColl);
Collections.sort(keyList);
for (String ky : keyList) {
String val = (String)pk.get(ky);
if (UtilValidate.isNotEmpty(val)) {
if (sig.length() > 0) sig.append("_");
sig.append(val);
}
}
if (UtilValidate.isNotEmpty(suffix)) {
if (sig.length() > 0) sig.append("_");
sig.append(suffix);
}
return sig.toString();
}
public static void setCurrentEntityMap(HttpServletRequest request, GenericEntity ent) {
String entityName = ent.getEntityName();
setCurrentEntityMap(request, entityName, ent);
}
public static void setCurrentEntityMap(HttpServletRequest request, String entityName, GenericEntity ent) {
HttpSession session = request.getSession();
Map<String, GenericEntity> currentEntityMap = UtilGenerics.checkMap(session.getAttribute("currentEntityMap"));
if (currentEntityMap == null) {
currentEntityMap = new HashMap<String, GenericEntity>();
session.setAttribute("currentEntityMap", currentEntityMap);
}
currentEntityMap.put(entityName, ent);
}
public static String getFromSomewhere(String name, Map<String, Object> paramMap, HttpServletRequest request, Map<String, Object> context) {
String ret = null;
if (paramMap != null) {
ret = (String)paramMap.get(name);
}
if (UtilValidate.isEmpty(ret)) {
Object obj = request.getAttribute(name);
if (obj != null) {
ret = obj.toString();
} else {
obj = context.get(name);
if (obj != null) {
ret = obj.toString();
}
}
}
return ret;
}
public static void getCurrentValue(HttpServletRequest request, Delegator delegator) {
HttpSession session = request.getSession();
Map<String, GenericPK> currentEntityMap = UtilGenerics.checkMap(session.getAttribute("currentEntityMap"));
if (currentEntityMap == null) {
currentEntityMap = new HashMap<String, GenericPK>();
session.setAttribute("currentEntityMap", currentEntityMap);
}
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String entityName = (String)paramMap.get("entityName");
if (UtilValidate.isEmpty(entityName)) {
entityName = (String)request.getAttribute("entityName");
}
GenericPK cachedPK = null;
if (UtilValidate.isNotEmpty(entityName)) {
cachedPK = currentEntityMap.get(entityName);
}
getCurrentValueWithCachedPK(request, delegator, cachedPK, entityName);
GenericPK currentPK = (GenericPK)request.getAttribute("currentPK");
currentEntityMap.put(entityName, currentPK);
}
public static void getCurrentValueWithCachedPK(HttpServletRequest request, Delegator delegator, GenericPK cachedPK, String entityName) {
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
// Build the primary key that may have been passed in as key values
GenericValue v = delegator.makeValue(entityName);
GenericPK passedPK = v.getPrimaryKey();
Collection<String> keyColl = passedPK.getAllKeys();
for (String attrName : keyColl) {
String attrVal = (String)request.getAttribute(attrName);
if (UtilValidate.isEmpty(attrVal)) {
attrVal = (String)paramMap.get(attrName);
}
if (UtilValidate.isNotEmpty(attrVal)) {
passedPK.put(attrName,attrVal);
}
}
// If a full passed primary key exists, it takes precedence over a cached key
// I cannot determine if the key testing utils of GenericEntity take into account
// whether or not a field is populated.
boolean useCached = false;
boolean usePassed = true;
if (cachedPK != null) {
useCached = true;
keyColl = cachedPK.getPrimaryKey().getAllKeys();
for (String ky : keyColl) {
String sCached = null;
String sPassed = null;
Object oPassed = null;
Object oCached = null;
oPassed = passedPK.get(ky);
if (oPassed != null) {
sPassed = oPassed.toString();
if (UtilValidate.isEmpty(sPassed)) {
// If any part of passed key is not available, it can't be used
usePassed = false;
} else {
oCached = cachedPK.get(ky);
if (oCached != null) {
sCached = oCached.toString();
if (UtilValidate.isEmpty(sCached)) {
useCached = false;
} else {
}
} else {
useCached = false;
}
}
} else {
//useCached = false;
usePassed = false;
}
}
}
GenericPK currentPK = null;
if (usePassed && useCached) {
currentPK = passedPK;
} else if (usePassed && !useCached) {
currentPK = passedPK;
} else if (!usePassed && useCached) {
currentPK = cachedPK;
}
if (currentPK != null) {
request.setAttribute("currentPK", currentPK);
GenericValue currentValue = null;
try {
currentValue = EntityQuery.use(delegator).from(currentPK.getEntityName()).where(currentPK).queryOne();
} catch (GenericEntityException e) {
}
request.setAttribute("currentValue", currentValue);
}
}
public static List<String []> getPermittedPublishPoints(Delegator delegator, List<GenericValue> allPublishPoints, GenericValue userLogin, Security security, String permittedAction, String permittedOperations, String passedRoles) throws GeneralException {
List<String []> permittedPublishPointList = new LinkedList<String[]>();
// Check that user has permission to admin sites
for (GenericValue webSitePP : allPublishPoints) {
String contentId = (String)webSitePP.get("contentId");
String templateTitle = (String)webSitePP.get("templateTitle");
GenericValue content = delegator.makeValue("Content", UtilMisc.toMap("contentId", contentId));
String statusId = null;
String entityAction = permittedAction;
if (entityAction == null) {
entityAction = "_ADMIN";
}
List<String> passedPurposes = UtilMisc.toList("ARTICLE");
List<String> roles = StringUtil.split(passedRoles, "|");
List<String> targetOperationList = new LinkedList<String>();
if (UtilValidate.isEmpty(permittedOperations)) {
targetOperationList.add("CONTENT" + entityAction);
} else {
targetOperationList = StringUtil.split(permittedOperations, "|");
}
Map<String, Object> results = null;
//if (Debug.infoOn()) Debug.logInfo("in getPermittedPublishPoints, content:" + content, module);
results = EntityPermissionChecker.checkPermission(content, statusId, userLogin, passedPurposes, targetOperationList, roles, delegator, security, entityAction);
String permissionStatus = (String)results.get("permissionStatus");
if (permissionStatus != null && permissionStatus.equalsIgnoreCase("granted")) {
String [] arr = {contentId,templateTitle};
permittedPublishPointList.add(arr);
}
}
return permittedPublishPointList;
}
/**
Returns a list of WebSitePublishPoint entities that are children of parentPubPt
The name should be "getAllTopLevelPublishPoints" or "getAllChildPublishPoints"
@param parentPubPt The parent publish point.
*/
public static List<GenericValue> getAllPublishPoints(Delegator delegator, String parentPubPt) throws GeneralException {
List<GenericValue> relatedPubPts = null;
try {
relatedPubPts = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentIdTo", parentPubPt, "contentAssocTypeId", "SUBSITE")
.cache().queryList();
} catch (GenericEntityException e) {
throw new GeneralException(e.getMessage());
}
List<GenericValue> allPublishPoints = new LinkedList<GenericValue>();
GenericValue webSitePublishPoint = null;
for (GenericValue contentAssoc : relatedPubPts) {
String pub = (String)contentAssoc.get("contentId");
//webSitePublishPoint = EntityQuery.use(delegator).from("WebSitePublishPoint").where("contentId", pub).cache().queryOne();
webSitePublishPoint = getWebSitePublishPoint(delegator, pub, false);
allPublishPoints.add(webSitePublishPoint);
}
return allPublishPoints;
}
public static Map<String, GenericValue> getPublishPointMap(Delegator delegator, String pubPtId) throws GeneralException {
List<GenericValue> publishPointList = getAllPublishPoints(delegator, pubPtId);
Map<String, GenericValue> publishPointMap = new HashMap<String, GenericValue>();
for (GenericValue webSitePublishPoint : publishPointList) {
String pub = (String)webSitePublishPoint.get("contentId");
publishPointMap.put(pub, webSitePublishPoint);
}
return publishPointMap;
}
public static void getAllPublishPointMap(Delegator delegator, String pubPtId, Map<String, GenericValue> publishPointMap) throws GeneralException {
List<GenericValue> publishPointList = getAllPublishPoints(delegator, pubPtId);
for (GenericValue webSitePublishPoint : publishPointList) {
String pub = (String)webSitePublishPoint.get("contentId");
publishPointMap.put(pub, webSitePublishPoint);
getAllPublishPointMap(delegator, pub, publishPointMap);
}
}
public static Map<String, GenericValue> getPublishPointMap(Delegator delegator, List<GenericValue> publishPointList) {
Map<String, GenericValue> publishPointMap = new HashMap<String, GenericValue>();
for (GenericValue webSitePublishPoint : publishPointList) {
String pub = (String)webSitePublishPoint.get("contentId");
publishPointMap.put(pub, webSitePublishPoint);
}
return publishPointMap;
}
public static List<Map<String, Object>> getStaticValues(Delegator delegator, String parentPlaceholderId, List<String []> permittedPublishPointList) throws GeneralException {
List<GenericValue> assocValueList = null;
try {
assocValueList = EntityQuery.use(delegator).from("Content").where("contentTypeId", parentPlaceholderId).cache().queryList();
} catch (GenericEntityException e) {
throw new GeneralException(e.getMessage());
}
List<Map<String, Object>> staticValueList = new LinkedList<Map<String,Object>>();
int counter = 0;
for (GenericValue content : assocValueList) {
String contentId = (String)content.get("contentId");
String contentName = (String)content.get("contentName");
String description = (String)content.get("description");
Map<String, Object> map = new HashMap<String, Object>();
map.put("contentId", contentId);
map.put("contentName", contentName);
map.put("description", description);
for (String [] publishPointArray : permittedPublishPointList) {
String publishPointId = publishPointArray[0];
List<GenericValue> contentAssocList = content.getRelated("ToContentAssoc", UtilMisc.toMap("contentId", publishPointId), null, false);
List<GenericValue> filteredList = EntityUtil.filterByDate(contentAssocList);
if (filteredList.size() > 0) {
map.put(publishPointId, "Y");
GenericValue assoc = filteredList.get(0);
Timestamp fromDate = (Timestamp)assoc.get("fromDate");
map.put(publishPointId + "FromDate", fromDate);
} else {
map.put(publishPointId, "N");
}
}
staticValueList.add(map);
counter++;
}
return staticValueList;
}
public static GenericValue getWebSitePublishPoint(Delegator delegator, String contentId) throws GenericEntityException {
return getWebSitePublishPoint(delegator, contentId, false);
}
public static GenericValue getWebSitePublishPoint(Delegator delegator, String contentId, boolean ignoreCache) throws GenericEntityException {
GenericValue webSitePublishPoint = null;
if (!ignoreCache)
webSitePublishPoint = cachedWebSitePublishPoints.get(contentId);
if (webSitePublishPoint == null) {
webSitePublishPoint = EntityQuery.use(delegator).from("WebSitePublishPoint").where("contentId", contentId).queryOne();
// If no webSitePublishPoint exists, still try to look for parent by making a dummy value
if (webSitePublishPoint == null) {
webSitePublishPoint = delegator.makeValue("WebSitePublishPoint", UtilMisc.toMap("contentId", contentId));
}
//if (Debug.infoOn()) Debug.logInfo("in getWebSitePublishPoint, contentId:" + contentId, module);
webSitePublishPoint = overrideWebSitePublishPoint(delegator, webSitePublishPoint);
cachedWebSitePublishPoints.put(contentId, webSitePublishPoint);
}
return webSitePublishPoint;
}
public static GenericValue overrideWebSitePublishPoint(Delegator delegator, GenericValue passedValue) throws GenericEntityException {
String contentId = passedValue.getString("contentId");
GenericValue webSitePublishPoint = passedValue;
String contentIdTo = getParentWebSitePublishPointId(delegator, contentId);
//if (Debug.infoOn()) Debug.logInfo("in overrideWebSitePublishPoint, contentIdTo:" + contentIdTo, module);
if (contentIdTo != null) {
//webSitePublishPoint = getWebSitePublishPoint(delegator, contentIdTo, false);
webSitePublishPoint = EntityQuery.use(delegator).from("WebSitePublishPoint").where("contentId", contentIdTo).cache().queryOne();
if (webSitePublishPoint != null) {
webSitePublishPoint = GenericValue.create(webSitePublishPoint);
webSitePublishPoint = overrideWebSitePublishPoint(delegator, webSitePublishPoint);
webSitePublishPoint.setNonPKFields(passedValue, false);
webSitePublishPoint.setPKFields(passedValue, false);
passedValue.setNonPKFields(webSitePublishPoint);
}
}
return webSitePublishPoint;
}
public static GenericValue getParentWebSitePublishPointValue(Delegator delegator, String contentId) throws GenericEntityException {
String contentIdTo = getParentWebSitePublishPointId(delegator, contentId);
GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentIdTo).cache().queryOne();
return content;
}
public static String getParentWebSitePublishPointId(Delegator delegator, String contentId) throws GenericEntityException {
String contentIdTo = null;
GenericValue contentAssoc = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", contentId, "contentAssocTypeId", "SUBSITE")
.filterByDate().cache().queryFirst();
if (contentAssoc != null) {
contentIdTo = contentAssoc.getString("contentIdTo");
}
return contentIdTo;
}
public static GenericValue getStaticValue(Delegator delegator, String parentPlaceholderId, String webSitePublishPointId, boolean ignoreCache) throws GenericEntityException {
GenericValue webSitePublishPoint = null;
// GenericValue staticValue = null;
if (!ignoreCache) {
Map<String, Object> subStaticValueMap = cachedStaticValues.get(parentPlaceholderId);
if (subStaticValueMap == null) {
subStaticValueMap = new HashMap<String, Object>();
cachedStaticValues.put(parentPlaceholderId, subStaticValueMap);
}
//Map staticValueMap = (GenericValue)cachedStaticValues.get(web);
}
/*
if (webSitePublishPoint == null) {
webSitePublishPoint = EntityQuery.use(delegator).from("WebSitePublishPoint").where("contentId", contentId).queryOne();
// If no webSitePublishPoint exists, still try to look for parent by making a dummy value
if (webSitePublishPoint == null) {
webSitePublishPoint = delegator.makeValue("WebSitePublishPoint", UtilMisc.toMap("contentId", contentId));
}
webSitePublishPoint = overrideStaticValues(delegator, webSitePublishPoint);
cachedWebSitePublishPoints.put(contentId, webSitePublishPoint);
}
*/
return webSitePublishPoint;
}
public static List<Object []> getPublishedLinks(Delegator delegator, String targContentId, String rootPubId, GenericValue userLogin, Security security, String permittedAction, String permittedOperations , String passedRoles) throws GeneralException {
// Set up one map with all the top-level publish points (to which only one sub point can be attached to)
// and another map (publishPointMapAll) that points to one of the top-level points.
List<GenericValue> allPublishPointList = getAllPublishPoints(delegator, rootPubId);
//if (Debug.infoOn()) Debug.logInfo("in getPublishLinks, allPublishPointList:" + allPublishPointList, module);
List<String []> publishPointList = getPermittedPublishPoints(delegator, allPublishPointList, userLogin, security , permittedAction, permittedOperations, passedRoles);
Map<String, Object> publishPointMap = new HashMap<String, Object>();
Map<String, Object> publishPointMapAll = new HashMap<String, Object>();
for (String [] arr : publishPointList) {
//GenericValue webSitePublishPoint = (GenericValue)it.next();
//String contentId = (String)webSitePublishPoint.get("contentId");
//String description = (String)webSitePublishPoint.get("description");
String contentId = arr[0];
String description = arr[1];
List<Object []> subPointList = new LinkedList<Object[]>();
Object nullObj = null;
Object [] subArr = {contentId, subPointList, description, nullObj};
publishPointMap.put(contentId, subArr);
publishPointMapAll.put(contentId, contentId);
List<GenericValue> subPublishPointList = getAllPublishPoints(delegator, contentId);
for (GenericValue webSitePublishPoint2 : subPublishPointList) {
//String [] arr2 = (String [])it2.next();
//String contentId2 = (String)arr2[0];
//String description2 = (String)arr2[1];
String contentId2 = (String)webSitePublishPoint2.get("contentId");
String description2 = (String)webSitePublishPoint2.get("templateTitle");
publishPointMapAll.put(contentId2, contentId);
Timestamp obj = null;
Object [] subArr2 = {contentId2, description2, obj};
subPointList.add(subArr2);
}
}
/* */
List<GenericValue> assocValueList = null;
try {
assocValueList = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", targContentId, "contentAssocTypeId", "PUBLISH_LINK")
.filterByDate().cache().queryList();
} catch (GenericEntityException e) {
throw new GeneralException(e.getMessage());
}
for (GenericValue contentAssoc : assocValueList) {
String contentIdTo = contentAssoc.getString("contentIdTo");
String topContentId = (String)publishPointMapAll.get(contentIdTo);
Object [] subArr = (Object [])publishPointMap.get(topContentId);
//if (Debug.infoOn()) Debug.logInfo("in getPublishLinks, subArr:" + Arrays.asList(subArr) , module);
if (contentIdTo.equals(topContentId)) {
subArr[3] = contentAssoc.get("fromDate");
} else {
if (subArr != null) {
List<Object []> subPointList = UtilGenerics.checkList(subArr[1]);
Iterator<Object []> it5 = subPointList.iterator();
Object [] subArr2 = null;
while (it5.hasNext()) {
subArr2 = it5.next();
String contentId5 = (String)subArr2[0];
if (contentId5.equals(contentIdTo))
break;
}
subArr2[2] = contentAssoc.get("fromDate");
}
}
}
List<Object []> publishedLinkList = new LinkedList<Object[]>();
for (String contentId : publishPointMap.keySet()) {
Object [] subPointArr = (Object [])publishPointMap.get(contentId);
publishedLinkList.add(subPointArr);
}
return publishedLinkList;
}
public static GenericValue getAuthorContent(Delegator delegator, String contentId) {
GenericValue authorContent = null;
try {
List<String> assocTypes = UtilMisc.toList("AUTHOR");
List<String> contentTypes = null;
// String fromDate = null;
// String thruDate = null;
Map<String, Object> results = ContentServicesComplex.getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, null, "To", null, null, assocTypes, contentTypes, Boolean.TRUE, null, null);
List<GenericValue> valueList = UtilGenerics.checkList(results.get("entityList"));
if (valueList.size() > 0) {
GenericValue value = valueList.get(0);
authorContent = delegator.makeValue("Content");
authorContent.setPKFields(value);
authorContent.setNonPKFields(value);
//if (Debug.infoOn()) Debug.logInfo("in getAuthorContent, authorContent:" + authorContent, module);
}
} catch (GenericEntityException e) {
} catch (MiniLangException e2) {
}
return authorContent;
}
public static List<String []> getPermittedDepartmentPoints(Delegator delegator, List<GenericValue> allDepartmentPoints, GenericValue userLogin, Security security, String permittedAction, String permittedOperations, String passedRoles) throws GeneralException {
List<String []> permittedDepartmentPointList = new LinkedList<String[]>();
// Check that user has permission to admin sites
for (GenericValue content : allDepartmentPoints) {
String contentId = (String)content.get("contentId");
String contentName = (String)content.get("contentName");
String statusId = null;
String entityAction = permittedAction;
if (entityAction == null)
entityAction = "_ADMIN";
List<String> passedPurposes = UtilMisc.<String>toList("ARTICLE");
List<String> roles = StringUtil.split(passedRoles, "|");
List<String> targetOperationList = new LinkedList<String>();
if (UtilValidate.isEmpty(permittedOperations)) {
targetOperationList.add("CONTENT" + entityAction);
} else {
targetOperationList = StringUtil.split(permittedOperations, "|");
}
Map<String, Object> results = null;
//if (Debug.infoOn()) Debug.logInfo("in getPermittedDepartmentPoints, content:" + content, module);
results = EntityPermissionChecker.checkPermission(content, statusId, userLogin, passedPurposes, targetOperationList, roles, delegator, security, entityAction);
String permissionStatus = (String)results.get("permissionStatus");
if (permissionStatus != null && permissionStatus.equalsIgnoreCase("granted")) {
String [] arr = {contentId,contentName};
permittedDepartmentPointList.add(arr);
}
}
return permittedDepartmentPointList;
}
/**
Returns a list of "department" (having ContentAssoc of type "DEPARTMENT")
Content entities that are children of parentPubPt
@param parentPubPt The parent publish point.
*/
public static List<GenericValue> getAllDepartmentContent(Delegator delegator, String parentPubPt) throws GeneralException {
List<GenericValue> relatedPubPts = null;
try {
relatedPubPts = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentIdTo", parentPubPt, "contentAssocTypeId", "DEPARTMENT")
.cache().queryList();
} catch (GenericEntityException e) {
throw new GeneralException(e.getMessage());
}
List<GenericValue> allDepartmentPoints = new LinkedList<GenericValue>();
GenericValue departmentContent = null;
for (GenericValue contentAssoc : relatedPubPts) {
String pub = (String)contentAssoc.get("contentId");
departmentContent = EntityQuery.use(delegator).from("Content").where("contentId", pub).cache().queryOne();
allDepartmentPoints.add(departmentContent);
}
return allDepartmentPoints;
}
public static String getUserName(HttpServletRequest request, String userLoginId) throws GenericEntityException {
String userName = null;
Delegator delegator = (Delegator)request.getAttribute("delegator");
GenericValue userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).cache().queryOne();
GenericValue person = userLogin.getRelatedOne("Person", true);
userName = person.getString("firstName") + " " + person.getString("lastName");
return userName;
}
public static int updateStatsTopDown(Delegator delegator, String contentId, List<String> typeList) throws GenericEntityException {
int subLeafCount = 0;
GenericValue thisContent = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
if (thisContent == null)
throw new RuntimeException("No entity found for id=" + contentId);
List<EntityCondition> conditionMain = new ArrayList<EntityCondition>();
conditionMain.add(EntityCondition.makeCondition("contentIdTo", contentId));
if (typeList.size() > 0) {
conditionMain.add(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList));
}
List<GenericValue> contentAssocs = EntityQuery.use(delegator).from("ContentAssoc").where(conditionMain)
.filterByDate().cache().queryList();
for (GenericValue contentAssoc : contentAssocs) {
String subContentId = contentAssoc.getString("contentId");
subLeafCount += updateStatsTopDown(delegator, subContentId, typeList);
}
// If no children, count this as a leaf
if (subLeafCount == 0)
subLeafCount = 1;
thisContent.put("childBranchCount", Long.valueOf(contentAssocs.size()));
thisContent.put("childLeafCount", Long.valueOf(subLeafCount));
thisContent.store();
return subLeafCount;
}
public static void updateStatsBottomUp(Delegator delegator, String contentId, List<String> typeList, int branchChangeAmount, int leafChangeAmount) throws GenericEntityException {
GenericValue thisContent = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
if (thisContent == null)
throw new RuntimeException("No entity found for id=" + contentId);
List<GenericValue> contentAssocs = EntityQuery.use(delegator).from("ContentAssoc")
.where(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList),
EntityCondition.makeCondition("contentId", EntityOperator.EQUALS, contentId))
.cache().filterByDate().queryList();
for (GenericValue contentAssoc : contentAssocs) {
String contentIdTo = contentAssoc.getString("contentIdTo");
GenericValue contentTo = EntityQuery.use(delegator).from("Content").where("contentId", contentIdTo).queryOne();
int intLeafCount = 0;
Long leafCount = (Long)contentTo.get("childLeafCount");
if (leafCount != null) {
intLeafCount = leafCount.intValue();
}
contentTo.set("childLeafCount", Long.valueOf(intLeafCount + leafChangeAmount));
if (branchChangeAmount != 0) {
int intBranchCount = 0;
Long branchCount = (Long)contentTo.get("childBranchCount");
if (branchCount != null) {
intBranchCount = branchCount.intValue();
}
contentTo.set("childBranchCount", Long.valueOf(intBranchCount + branchChangeAmount));
}
contentTo.store();
updateStatsBottomUp(delegator, contentIdTo, typeList, 0, leafChangeAmount);
}
}
}
@@ -0,0 +1,393 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
public class ConvertTree{
public static final String module = ConvertTree.class.getName();
/*
This program will convert the output of the DOS 'tree' command into a contantAssoc tree.
the leaves in the tree will point to filenames on the local disk.
With this program and the content navigation a office file server can be replaced with a
document tree in OFBiz. From that point on the documents can be connected to the cutomers,
orders, invoices etc..
In order ta make this service active add the following to the service definition file:
<service name="convertTree" auth="true" engine="java" invoke="convertTree" transaction-timeout="3600"
location="org.ofbiz.content.tree.ConvertTree">
<description>Convert DOS tree output to ContentAssoc tree.</description>
<attribute name="file" type="String" mode="IN" optional="false"/>
</service>
*/
public static Map<String, Object> convertTree(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String file = (String) context.get("file");
String errMsg = "", sucMsg= "";
GenericValue Entity = null;
try {
BufferedReader input = null;
try {
if (!UtilValidate.isEmpty(file)) {
input = new BufferedReader(new FileReader(file));
String line = null;
int size = 0;
if (file != null) {
int counterLine = 0;
//Home Document
Entity = null;
Entity = delegator.makeValue("Content");
Entity.set("contentId", "ROOT");
Entity.set("contentName", "ROOT");
Entity.set("contentTypeId", "DOCUMENT");
Entity.set("createdByUserLogin", userLogin.get("userLoginId"));
Entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId"));
Entity.set("createdDate", UtilDateTime.nowTimestamp());
Entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp());
Entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp());
Entity.set("createdStamp", UtilDateTime.nowTimestamp());
Entity.set("createdTxStamp", UtilDateTime.nowTimestamp());
delegator.create(Entity);
Entity = null;
Entity = delegator.makeValue("Content");
Entity.set("contentId", "HOME_DUCUMENT");
Entity.set("contentName", "Home");
Entity.set("contentTypeId", "DOCUMENT");
Entity.set("createdByUserLogin", userLogin.get("userLoginId"));
Entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId"));
Entity.set("createdDate", UtilDateTime.nowTimestamp());
Entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp());
Entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp());
Entity.set("createdStamp", UtilDateTime.nowTimestamp());
Entity.set("createdTxStamp", UtilDateTime.nowTimestamp());
delegator.create(Entity);
Map<String, Object> contentAssoc = new HashMap<String, Object>();
contentAssoc.put("contentId", "HOME_DUCUMENT");
contentAssoc.put("contentAssocTypeId", "TREE_CHILD");
contentAssoc.put("contentIdTo", "ROOT");
contentAssoc.put("userLogin", userLogin);
dispatcher.runSync("createContentAssoc", contentAssoc);
int recordCount = 0;
while ((line = input.readLine()) != null) {//start line
boolean hasFolder = true;
String rootContent = null, contentId = null; counterLine++;
if (counterLine > 1) {
size = line.length();
String check = "\\", checkSubContent = ",", contentName = "", contentNameInprogress = "", data = line.substring(3, size);
//Debug.logInfo("======Data======"+data);
size = data.length();
for (int index = 0; index< size; index++) {//start character in line
boolean contentNameMatch = false;
int contentAssocSize = 0;
List<GenericValue> contentAssocs = null;
if (data.charAt(index) == check.charAt(0) || data.charAt(index) == checkSubContent.charAt(0)) {//store data
contentName = contentName + contentNameInprogress;
if (contentName.length() > 100) {
contentName = contentName.substring(0, 100);
}
//check duplicate folder
GenericValue content = EntityQuery.use(delegator).from("Content").where("contentName", contentName).queryFirst();
if (content != null) {
contentId = content.getString("contentId");
}
if (content != null && hasFolder==true) {
if (rootContent != null) {
contentAssocs = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", contentId, "contentIdTo", rootContent)
.queryList();
List<GenericValue> contentAssocCheck = EntityQuery.use(delegator).from("ContentAssoc").where("contentIdTo", rootContent).queryList();
Iterator<GenericValue> contentAssChecks = contentAssocCheck.iterator();
while (contentAssChecks.hasNext() && contentNameMatch == false) {
GenericValue contentAss = contentAssChecks.next();
GenericValue contentcheck = EntityQuery.use(delegator).from("Content").where("contentId", contentAss.get("contentId")).queryOne();
if (contentcheck!=null) {
if (contentcheck.get("contentName").equals(contentName) && contentNameMatch == false) {
contentNameMatch = true;
contentId = contentcheck.get("contentId").toString();
}
}
}
} else {
rootContent = "HOME_DUCUMENT";
contentAssocs = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", contentId, "contentIdTo", rootContent)
.queryList();
}
contentAssocSize = contentAssocs.size();
}
if (contentAssocSize == 0 && contentNameMatch == false) {//New Root Content
Entity = null;
contentId = delegator.getNextSeqId("Content");
Entity = delegator.makeValue("Content");
Entity.set("contentId", contentId);
Entity.set("contentName", contentName);
Entity.set("contentTypeId", "DOCUMENT");
Entity.set("createdByUserLogin", userLogin.get("userLoginId"));
Entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId"));
Entity.set("createdDate", UtilDateTime.nowTimestamp());
delegator.create(Entity);
hasFolder = false;
} else {
//Debug.logInfo("Content Name = [ " + contentId + "] already exist.");//ShoW log file
hasFolder = true;
}
//Relation Content
if (rootContent == null) {
rootContent = "HOME_DUCUMENT";
}
contentAssocs = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", contentId,
"contentIdTo", rootContent,
"contentAssocTypeId", "TREE_CHILD")
.queryList();
if (contentAssocs.size() == 0) {
contentAssoc = new HashMap<String, Object>();
contentAssoc.put("contentId", contentId);
contentAssoc.put("contentAssocTypeId", "TREE_CHILD");
contentAssoc.put("contentIdTo", rootContent);
contentAssoc.put("userLogin", userLogin);
dispatcher.runSync("createContentAssoc", contentAssoc);
rootContent = contentId;
} else {
//Debug.logInfo("ContentAssoc [contentId= " + contentId + ", contentIdTo=" + rootContent + "] already exist.");//ShoW log file
rootContent=contentId;
}
contentName = "";
contentNameInprogress ="";
}
if (data.charAt(index)== checkSubContent.charAt(0)) {//Have sub content
createSubContent(index, data, rootContent, context, dctx);
index = size;
continue;
}
if ((data.charAt(index)) != check.charAt(0)) {
contentNameInprogress = contentNameInprogress.concat(Character.toString(data.charAt(index)));
if (contentNameInprogress.length() > 99) {
contentName = contentName + contentNameInprogress;
contentNameInprogress ="";
}
}
}//end character in line
recordCount++;
}
}//end line
sucMsg = "Convert Documents Tree Successful.<br/>Total : " + counterLine + " rows";
}
}
}
finally {
input.close();
}
return ServiceUtil.returnSuccess(sucMsg);
} catch (IOException e) {
errMsg = "IOException "+ UtilMisc.toMap("errMessage", e.toString());
Debug.logError(e, errMsg, module);
return ServiceUtil.returnError(errMsg);
} catch (GenericServiceException e) {
errMsg = "GenericServiceException "+ UtilMisc.toMap("errMessage", e.toString());
Debug.logError(e, errMsg, module);
return ServiceUtil.returnError(errMsg);
} catch (GenericEntityException e) {
errMsg = "GenericEntityException "+ UtilMisc.toMap("errMessage", e.toString());
Debug.logError(e, errMsg, module);
e.printStackTrace();
return ServiceUtil.returnError(errMsg);
}
}
public static Map<String,Object> createSubContent(int index, String line, String rootContent, Map<String, ? extends Object> context, DispatchContext dctx) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String subContents = null, check = ",", oldChar = "\"", newChar = "", contentNameInprogress = "", contentName = "", contentId = null;
GenericValue Entity = null;
String errMsg = "", sucMsg= "";
subContents = line.substring(index + 1, line.length());
subContents = subContents.replace(oldChar, newChar);
int size = subContents.length();
try {
for (index = 0; index < size; index++) {//start character in line
boolean contentNameMatch = false;
if (subContents.charAt(index) == check.charAt(0)) {//store data
contentName = contentName + contentNameInprogress;
//Debug.logInfo("subcontentName---->"+contentName);
if (contentName.length()>100) {
contentName = contentName.substring(0,100);
}
List<GenericValue> contents = EntityQuery.use(delegator).from("Content").where("contentName", contentName).orderBy("-contentId").queryList();
if (contents != null) {
Iterator<GenericValue> contentCheck = contents.iterator();
while (contentCheck.hasNext() && contentNameMatch == false) {
GenericValue contentch = contentCheck.next();
if (contentch != null) {
List<GenericValue> contentAssocsChecks = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", contentch.get("contentId"), "contentIdTo", rootContent)
.queryList();
if (contentAssocsChecks.size() > 0) {
contentNameMatch = true;
}
}
}
}
contentId = null;
if (contentNameMatch == false) {
//create DataResource
Map<String,Object> data = new HashMap<String, Object>();
data.put("userLogin", userLogin);
String dataResourceId = dispatcher.runSync("createDataResource", data).get("dataResourceId").toString();
//Debug.logInfo("==dataResourceId" + dataResourceId);
//create Content
contentId = delegator.getNextSeqId("Content");
Entity = null;
Entity = delegator.makeValue("Content");
Entity.set("contentId", contentId);
Entity.set("contentName", contentName);
Entity.set("contentTypeId", "DOCUMENT");
Entity.set("dataResourceId", dataResourceId);
Entity.set("createdByUserLogin", userLogin.get("userLoginId"));
Entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId"));
Entity.set("createdDate", UtilDateTime.nowTimestamp());
Entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp());
Entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp());
Entity.set("createdStamp", UtilDateTime.nowTimestamp());
Entity.set("createdTxStamp", UtilDateTime.nowTimestamp());
delegator.create(Entity);
//Relation Content
Map<String,Object> contentAssoc = new HashMap<String, Object>();
contentAssoc.put("contentId", contentId);
contentAssoc.put("contentAssocTypeId", "SUB_CONTENT");
contentAssoc.put("contentIdTo", rootContent);
contentAssoc.put("userLogin", userLogin);
dispatcher.runSync("createContentAssoc", contentAssoc);
}
contentName ="";
contentNameInprogress="";
}
if ((subContents.charAt(index) )!= check.charAt(0)) {
contentNameInprogress = contentNameInprogress.concat(Character.toString(subContents.charAt(index)));
if (contentNameInprogress.length() > 99) {
contentName = contentName + contentNameInprogress;
contentNameInprogress = "";
}
}
//lastItem
if (index == size - 1) {
contentNameMatch = false;
List<GenericValue> contents = EntityQuery.use(delegator).from("Content").where("contentName", contentName).queryList();
if (contents != null) {
Iterator<GenericValue> contentCheck = contents.iterator();
while (contentCheck.hasNext() && contentNameMatch == false) {
GenericValue contentch = contentCheck.next();
if (contentch != null) {
long contentAssocCount = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", contentch.get("contentId"), "contentIdTo", rootContent)
.queryCount();
if (contentAssocCount > 0) {
contentNameMatch = true;
}
}
}
}
contentId = null;
if (contentNameMatch == false) {
//create DataResource
Map<String,Object> data = new HashMap<String, Object>();
data.put("userLogin", userLogin);
String dataResourceId = dispatcher.runSync("createDataResource",data).get("dataResourceId").toString();
//Debug.logInfo("==dataResourceId" + dataResourceId);
//create Content
contentId = delegator.getNextSeqId("Content");
Entity = null;
Entity = delegator.makeValue("Content");
Entity.set("contentId", contentId);
Entity.set("contentName", contentName);
Entity.set("contentTypeId", "DOCUMENT");
Entity.set("dataResourceId", dataResourceId);
Entity.set("createdByUserLogin", userLogin.get("userLoginId"));
Entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId"));
Entity.set("createdDate", UtilDateTime.nowTimestamp());
Entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp());
Entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp());
Entity.set("createdStamp", UtilDateTime.nowTimestamp());
Entity.set("createdTxStamp", UtilDateTime.nowTimestamp());
delegator.create(Entity);
//create ContentAssoc
Map<String,Object> contentAssoc = new HashMap<String, Object>();
contentAssoc.put("contentId", contentId);
contentAssoc.put("contentAssocTypeId", "SUB_CONTENT");
contentAssoc.put("contentIdTo", rootContent);
contentAssoc.put("userLogin", userLogin);
dispatcher.runSync("createContentAssoc", contentAssoc);
}
}
}
return ServiceUtil.returnSuccess(sucMsg);
} catch (GenericEntityException e) {
errMsg = "GenericEntityException "+ UtilMisc.toMap("errMessage", e.toString());
Debug.logError(e, errMsg, module);
e.printStackTrace();
return ServiceUtil.returnError(errMsg);
} catch (GenericServiceException e) {
errMsg = "GenericServiceException"+ UtilMisc.toMap("errMessage", e.toString());
Debug.logError(e, errMsg, module);
e.printStackTrace();
return ServiceUtil.returnError(errMsg);
}
}
}
@@ -0,0 +1,145 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.ofbiz.content.blog;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
/**
* BlogRssServices
*/
public class BlogRssServices {
public static final String module = BlogRssServices.class.getName();
public static final String resource = "ContentUiLabels";
public static final String mimeTypeId = "text/html";
public static final String mapKey = "SUMMARY";
public static Map<String, Object> generateBlogRssFeed(DispatchContext dctx, Map<String, ? extends Object> context) {
GenericValue userLogin = (GenericValue) context.get("userLogin");
String contentId = (String) context.get("blogContentId");
String entryLink = (String) context.get("entryLink");
String feedType = (String) context.get("feedType");
Locale locale = (Locale) context.get("locale");
// create the main link
String mainLink = (String) context.get("mainLink");
mainLink = mainLink + "?blogContentId=" + contentId;
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
// get the main blog content
GenericValue content = null;
try {
content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (content == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"ContentCannotGenerateBlogRssFeed",
UtilMisc.toMap("contentId", contentId), locale));
}
// create the feed
SyndFeed feed = new SyndFeedImpl();
feed.setFeedType(feedType);
feed.setLink(mainLink);
feed.setTitle(content.getString("contentName"));
feed.setDescription(content.getString("description"));
feed.setEntries(generateEntryList(dispatcher, delegator, contentId, entryLink, locale, userLogin));
Map<String, Object> resp = ServiceUtil.returnSuccess();
resp.put("wireFeed", feed.createWireFeed());
return resp;
}
public static List<SyndEntry> generateEntryList(LocalDispatcher dispatcher, Delegator delegator, String contentId, String entryLink, Locale locale, GenericValue userLogin) {
List<SyndEntry> entries = new LinkedList<SyndEntry>();
List<GenericValue> contentRecs = null;
try {
contentRecs = EntityQuery.use(delegator).from("ContentAssocViewTo")
.where("contentIdStart", contentId,
"caContentAssocTypeId", "PUBLISH_LINK",
"statusId", "CTNT_PUBLISHED")
.orderBy("-caFromDate").queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (contentRecs != null) {
for (GenericValue v : contentRecs) {
String sub = null;
try {
Map<String, Object> dummy = new HashMap<String, Object>();
sub = ContentWorker.renderSubContentAsText(dispatcher, delegator, v.getString("contentId"), mapKey, dummy, locale, mimeTypeId, true);
} catch (GeneralException e) {
Debug.logError(e, module);
} catch (IOException e) {
Debug.logError(e, module);
}
if (sub != null) {
String thisLink = entryLink + "?articleContentId=" + v.getString("contentId") + "&blogContentId=" + contentId;
SyndContent desc = new SyndContentImpl();
desc.setType("text/plain");
desc.setValue(sub);
SyndEntry entry = new SyndEntryImpl();
entry.setTitle(v.getString("contentName"));
entry.setPublishedDate(v.getTimestamp("createdDate"));
entry.setDescription(desc);
entry.setLink(thisLink);
entry.setAuthor((v.getString("createdByUserLogin")));
entries.add(entry);
}
}
}
return entries;
}
}
@@ -0,0 +1,414 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.ofbiz.content.cms;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Locale;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.GeneralRuntimeException;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.collections.MapStack;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.entity.util.EntityUtilProperties;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.webapp.control.RequestHandler;
import org.ofbiz.webapp.website.WebSiteWorker;
import org.ofbiz.widget.renderer.FormStringRenderer;
import org.ofbiz.widget.renderer.ScreenRenderer;
import org.ofbiz.widget.renderer.macro.MacroFormRenderer;
import freemarker.template.TemplateException;
/**
* CmsEvents
*/
public class CmsEvents {
public static final String module = CmsEvents.class.getName();
public static String cms(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
ServletContext servletContext = request.getSession().getServletContext();
HttpSession session = request.getSession();
String webSiteId = (String) session.getAttribute("webSiteId");
if (webSiteId == null) {
webSiteId = WebSiteWorker.getWebSiteId(request);
if (webSiteId == null) {
request.setAttribute("_ERROR_MESSAGE_", "Not able to run CMS application; no webSiteId defined for WebApp!");
return "error";
}
}
// is this a default request or called from a defined request mapping
String targetRequest = (String) request.getAttribute("targetRequestUri");
String actualRequest = (String) request.getAttribute("thisRequestUri");
if (targetRequest != null) {
targetRequest = targetRequest.replaceAll("\\W", "");
} else {
targetRequest = "";
}
if (actualRequest != null) {
actualRequest = actualRequest.replaceAll("\\W", "");
} else {
actualRequest = "";
}
// place holder for the content id
String contentId = null;
String mapKey = null;
String pathInfo = null;
// If an override view is present then use that in place of request.getPathInfo()
String overrideViewUri = (String) request.getAttribute("_CURRENT_CHAIN_VIEW_");
if (UtilValidate.isNotEmpty(overrideViewUri)) {
pathInfo = overrideViewUri;
} else {
pathInfo = request.getPathInfo();
if (targetRequest.equals(actualRequest) && pathInfo != null) {
// was called directly -- path info is everything after the request
String[] pathParsed = pathInfo.split("/", 3);
if (pathParsed.length > 2) {
pathInfo = pathParsed[2];
} else {
pathInfo = null;
}
} // if called through the default request, there is no request in pathinfo
}
// if path info is null; check for a default content
if (pathInfo == null) {
GenericValue defaultContent = null;
try {
defaultContent = EntityQuery.use(delegator).from("WebSiteContent")
.where("webSiteId", webSiteId, "webSiteContentTypeId", "DEFAULT_PAGE")
.orderBy("-fromDate").filterByDate().cache().queryFirst();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (defaultContent != null) {
pathInfo = defaultContent.getString("contentId");
}
}
// check for path alias first
if (pathInfo != null) {
// clean up the pathinfo for parsing
pathInfo = pathInfo.trim();
if (pathInfo.startsWith("/")) {
pathInfo = pathInfo.substring(1);
}
if (pathInfo.endsWith("/")) {
pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
}
GenericValue pathAlias = null;
try {
pathAlias = EntityQuery.use(delegator).from("WebSitePathAlias").where("webSiteId", webSiteId, "pathAlias", pathInfo).orderBy("-fromDate").cache().filterByDate().queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (pathAlias != null) {
String alias = pathAlias.getString("aliasTo");
contentId = pathAlias.getString("contentId");
mapKey = pathAlias.getString("mapKey");
if (contentId == null && UtilValidate.isNotEmpty(alias)) {
if (!alias.startsWith("/")) {
alias = "/" + alias;
}
RequestDispatcher rd = request.getRequestDispatcher(request.getServletPath() + alias);
try {
rd.forward(request, response);
} catch (ServletException e) {
Debug.logError(e, module);
return "error";
} catch (IOException e) {
Debug.logError(e, module);
return "error";
}
return null; // null to not process any views
}
}
// process through CMS -- using the mapKey (for now)
Locale locale = UtilHttp.getLocale(request);
// get the contentId/mapKey from URL
if (contentId == null) {
if (Debug.verboseOn()) Debug.logVerbose("Current PathInfo: " + pathInfo, module);
String[] pathSplit = pathInfo.split("/");
if (Debug.verboseOn()) Debug.logVerbose("Split pathinfo: " + pathSplit.length, module);
contentId = pathSplit[0];
if (pathSplit.length > 1) {
mapKey = pathSplit[1];
}
}
// verify the request content is associated with the current website
int statusCode = -1;
boolean hasErrorPage = false;
if (contentId != null) {
try {
statusCode = verifyContentToWebSite(delegator, webSiteId, contentId);
} catch (GeneralException e) {
Debug.logError(e, module);
throw new GeneralRuntimeException(e.getMessage(), e);
}
} else {
statusCode = HttpServletResponse.SC_NOT_FOUND;
}
// We try to find a specific Error page for this website concerning the status code
if (statusCode != HttpServletResponse.SC_OK) {
GenericValue errorContainer = null;
try {
errorContainer = EntityQuery.use(delegator).from("WebSiteContent")
.where("webSiteId", webSiteId, "webSiteContentTypeId", "ERROR_ROOT")
.orderBy("fromDate").filterByDate().cache().queryFirst();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (errorContainer != null) {
if (Debug.verboseOn()) Debug.logVerbose("Found error containers: " + errorContainer, module);
GenericValue errorPage = null;
try {
errorPage = EntityQuery.use(delegator).from("ContentAssocViewTo")
.where("contentIdStart", errorContainer.getString("contentId"),
"caContentAssocTypeId", "TREE_CHILD",
"contentTypeId", "DOCUMENT",
"caMapKey", String.valueOf(statusCode))
.filterByDate().queryFirst();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (errorPage != null) {
if (Debug.verboseOn())
Debug.logVerbose("Found error pages " + statusCode + " : " + errorPage, module);
contentId = errorPage.getString("contentId");
} else {
if (Debug.verboseOn())
Debug.logVerbose("No specific error page, falling back to the Error Container for " + statusCode, module);
contentId = errorContainer.getString("contentId");
}
mapKey = null;
hasErrorPage = true;
}
// We try to find a generic content Error page concerning the status code
if (!hasErrorPage) {
try {
GenericValue errorPage = EntityQuery.use(delegator).from("Content").where("contentId", "CONTENT_ERROR_" + statusCode).cache().queryOne();
if (errorPage != null) {
Debug.logVerbose("Found generic page " + statusCode, module);
contentId = errorPage.getString("contentId");
mapKey = null;
hasErrorPage = true;
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
}
if (statusCode == HttpServletResponse.SC_OK || hasErrorPage) {
// create the template map
MapStack<String> templateMap = MapStack.create();
ScreenRenderer.populateContextForRequest(templateMap, null, request, response, servletContext);
templateMap.put("statusCode", statusCode);
// make the link prefix
ServletContext ctx = (ServletContext) request.getAttribute("servletContext");
RequestHandler rh = (RequestHandler) ctx.getAttribute("_REQUEST_HANDLER_");
templateMap.put("_REQUEST_HANDLER_", rh);
response.setStatus(statusCode);
// NOTE DEJ20080817: this is done in the ContentMapFacade class now to avoid problems with the jsessionid being in the middle of the URL and such
//String contextLinkPrefix = rh.makeLink(request, response, "", true, false, true);
//templateMap.put("_CONTEXT_LINK_PREFIX_", contextLinkPrefix);
try {
Writer writer = response.getWriter();
// TODO: replace "screen" to support dynamic rendering of different output
FormStringRenderer formStringRenderer = new MacroFormRenderer(EntityUtilProperties.getPropertyValue("widget", "screen.formrenderer", delegator), request, response);
templateMap.put("formStringRenderer", formStringRenderer);
// if use web analytics
List<GenericValue> webAnalytics = EntityQuery.use(delegator).from("WebAnalyticsConfig").where("webSiteId", webSiteId).queryList();
// render
if (UtilValidate.isNotEmpty(webAnalytics) && hasErrorPage) {
ContentWorker.renderContentAsText(dispatcher, delegator, contentId, writer, templateMap, locale, "text/html", null, null, true, webAnalytics);
} else if (UtilValidate.isEmpty(mapKey)) {
ContentWorker.renderContentAsText(dispatcher, delegator, contentId, writer, templateMap, locale, "text/html", null, null, true);
} else {
ContentWorker.renderSubContentAsText(dispatcher, delegator, contentId, writer, mapKey, templateMap, locale, "text/html", true);
}
} catch (TemplateException e) {
throw new GeneralRuntimeException(String.format("Error creating form renderer while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
} catch (IOException e) {
throw new GeneralRuntimeException(String.format("Error in the response writer/output stream while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
} catch (GeneralException e) {
throw new GeneralRuntimeException(String.format("Error rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
}
return "success";
} else {
String contentName = null;
String siteName = null;
try {
GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
if (content != null && UtilValidate.isNotEmpty(content)) {
contentName = content.getString("contentName");
} else {
request.setAttribute("_ERROR_MESSAGE_", "Content: " + contentName + " [" + contentId + "] is not a publish point for the current website: [" + webSiteId + "]");
return "error";
}
siteName = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne().getString("siteName");
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
request.setAttribute("_ERROR_MESSAGE_", "Content: " + contentName + " [" + contentId + "] is not a publish point for the current website: " + siteName + " [" + webSiteId + "]");
return "error";
}
}
String siteName = null;
GenericValue webSite = null;
try {
webSite = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne();
if (webSite != null) {
siteName = webSite.getString("siteName");
}
if (siteName == null) {
siteName = "Not specified";
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (webSite != null) {
request.setAttribute("_ERROR_MESSAGE_", "Not able to find a page to display for website: " + siteName + " [" + webSiteId + "] not even a default page!");
} else {
request.setAttribute("_ERROR_MESSAGE_", "Not able to find a page to display, not even a default page AND the website entity record for WebSiteId:" + webSiteId + " could not be found");
}
return "error";
}
protected static int verifyContentToWebSite(Delegator delegator, String webSiteId, String contentId) throws GeneralException {
// first check if the passed in contentId is a publish point for the web site
List<GenericValue> publishPoints = null;
boolean hadContent = false;
try {
publishPoints = EntityQuery.use(delegator).from("WebSiteContent")
.where("webSiteId", webSiteId, "contentId", contentId, "webSiteContentTypeId", "PUBLISH_POINT")
.orderBy("-fromDate").cache().queryList();
} catch (GenericEntityException e) {
throw e;
}
if (UtilValidate.isNotEmpty(publishPoints)) {
hadContent = true;
}
publishPoints = EntityUtil.filterByDate(publishPoints);
if (UtilValidate.isNotEmpty(publishPoints)) {
if (Debug.verboseOn()) Debug.logVerbose("Found publish points: " + publishPoints, module);
return HttpServletResponse.SC_OK;
} else {
// the passed in contentId is not a publish point for the web site;
// however we will publish its content if it is a node of one of the trees that have a publish point as the root
List<GenericValue> topLevelContentValues = EntityQuery.use(delegator).from("WebSiteContent")
.where("webSiteId", webSiteId, "webSiteContentTypeId", "PUBLISH_POINT")
.orderBy("-fromDate").cache().filterByDate().queryList();
if (topLevelContentValues != null) {
for (GenericValue point : topLevelContentValues) {
int subContentStatusCode = verifySubContent(delegator, contentId, point.getString("contentId"));
if (subContentStatusCode == HttpServletResponse.SC_OK) {
return HttpServletResponse.SC_OK;
} else if (subContentStatusCode == HttpServletResponse.SC_GONE) {
hadContent = true;
}
}
}
}
int responseCode;
if (hadContent) {
responseCode = HttpServletResponse.SC_GONE;
} else {
responseCode = HttpServletResponse.SC_NOT_FOUND;
}
Debug.logWarning("Could not verify contentId [" + contentId + "] to webSiteId [" + webSiteId + "], returning code: " + responseCode, module);
return responseCode;
}
protected static int verifySubContent(Delegator delegator, String contentId, String contentIdFrom) throws GeneralException {
List<GenericValue> contentAssoc = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", contentIdFrom, "contentIdTo", contentId, "contentAssocTypeId", "SUB_CONTENT")
.cache().queryList();
boolean hadContent = false;
if (UtilValidate.isNotEmpty(contentAssoc)) {
hadContent = true;
}
contentAssoc = EntityUtil.filterByDate(contentAssoc);
if (UtilValidate.isEmpty(contentAssoc)) {
List<GenericValue> assocs = EntityQuery.use(delegator).from("ContentAssoc").where("contentId", contentIdFrom).cache().filterByDate().queryList();
if (assocs != null) {
for (GenericValue assoc : assocs) {
int subContentStatusCode = verifySubContent(delegator, contentId, assoc.getString("contentIdTo"));
if (subContentStatusCode == HttpServletResponse.SC_OK) {
return HttpServletResponse.SC_OK;
} else if (subContentStatusCode == HttpServletResponse.SC_GONE) {
hadContent = true;
}
}
}
} else {
if (Debug.verboseOn()) Debug.logVerbose("Found assocs: " + contentAssoc, module);
return HttpServletResponse.SC_OK;
}
if (hadContent) return HttpServletResponse.SC_GONE;
return HttpServletResponse.SC_NOT_FOUND;
}
}
@@ -0,0 +1,184 @@
package org.ofbiz.content.cms;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.CollectionUtils;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.ofbiz.base.lang.JSON;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericEntityNotFoundException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.transaction.TransactionUtil;
import org.ofbiz.entity.util.EntityUtil;
public class ContentJsonEvents {
public static final int CONTENT_NAME_MAX_LENGTH = 27;
public static String getContentAssocs(HttpServletRequest request, HttpServletResponse response) throws GenericEntityException, IOException {
Delegator delegator = (Delegator) request.getAttribute("delegator");
String contentId = request.getParameter("contentId");
EntityCondition condition = EntityCondition.makeCondition(
EntityCondition.makeCondition(UtilMisc.toMap("contentId", contentId)),
EntityUtil.getFilterByDateExpr()
);
List<GenericValue> assocs = delegator.findList("ContentAssoc", condition, null, null, null, false);
List<Map<String, Object>> nodes = new LinkedList<Map<String, Object>>();
for (GenericValue assoc : assocs) {
nodes.add(getTreeNode(assoc));
}
Collections.sort(nodes, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> node1, Map<String, Object> node2) {
Map<String, Object> data1 = UtilGenerics.cast(node1.get("data"));
Map<String, Object> data2 = UtilGenerics.cast(node2.get("data"));
if (data1 == null || data2 == null) {
return 0;
}
String title1 = (String) data1.get("title");
String title2 = (String) data2.get("title");
if (title1 == null || title2 == null) {
return 0;
}
return title1.toLowerCase().compareTo(title2.toLowerCase());
}
});
IOUtils.write(JSON.from(nodes).toString(), response.getOutputStream());
return "success";
}
public static String moveContent(HttpServletRequest request, HttpServletResponse response) throws GenericEntityException, IOException {
final Delegator delegator = (Delegator) request.getAttribute("delegator");
final String contentIdTo = request.getParameter("contentIdTo");
final String contentIdFrom = request.getParameter("contentIdFrom");
final String contentIdFromNew = request.getParameter("contentIdFromNew");
final String contentAssocTypeId = request.getParameter("contentAssocTypeId");
final Timestamp fromDate = Timestamp.valueOf(request.getParameter("fromDate"));
final Timestamp now = UtilDateTime.nowTimestamp();
GenericValue assoc = TransactionUtil.inTransaction(new Callable<GenericValue>() {
@Override
public GenericValue call() throws Exception {
GenericValue oldAssoc = delegator.findOne("ContentAssoc", UtilMisc.toMap("contentIdTo", contentIdTo, "contentId", contentIdFrom, "contentAssocTypeId", contentAssocTypeId, "fromDate", fromDate), false);
if (oldAssoc == null) {
throw new GenericEntityNotFoundException("Could not find ContentAssoc by primary key [contentIdTo: $contentIdTo, contentId: $contentIdFrom, contentAssocTypeId: $contentAssocTypeId, fromDate: $fromDate]");
}
GenericValue newAssoc = (GenericValue) oldAssoc.clone();
oldAssoc.set("thruDate", now);
oldAssoc.store();
newAssoc.set("contentId", contentIdFromNew);
newAssoc.set("fromDate", now);
newAssoc.set("thruDate", null);
delegator.clearCacheLine(delegator.create(newAssoc));
return newAssoc;
}
}, String.format("move content [%s] from [%s] to [%s]", contentIdTo, contentIdFrom, contentIdFromNew), 0, true).call();
IOUtils.write(JSON.from(getTreeNode(assoc)).toString(), response.getOutputStream());
return "success";
}
public static String deleteContent(HttpServletRequest request, HttpServletResponse response) throws GenericEntityException {
Delegator delegator = (Delegator) request.getAttribute("delegator");
String contentId = request.getParameter("contentId");
deleteContent(delegator, contentId);
return "success";
}
public static void deleteContent(Delegator delegator, String contentId) throws GenericEntityException {
Timestamp now = UtilDateTime.nowTimestamp();
EntityCondition condition = EntityCondition.makeCondition(
EntityCondition.makeCondition(UtilMisc.toMap("contentIdTo", contentId)),
EntityUtil.getFilterByDateExpr()
);
List<GenericValue> assocs = delegator.findList("ContentAssoc", condition, null, null, null, true);
for (GenericValue assoc : assocs) {
assoc.set("thruDate", now);
delegator.store(assoc);
}
deleteWebPathAliases(delegator, contentId);
}
private static void deleteWebPathAliases(Delegator delegator, String contentId) throws GenericEntityException {
Timestamp now = UtilDateTime.nowTimestamp();
EntityCondition condition = EntityCondition.makeCondition(
EntityCondition.makeCondition(UtilMisc.toMap("contentId", contentId)),
EntityUtil.getFilterByDateExpr()
);
List<GenericValue> pathAliases = delegator.findList("WebSitePathAlias", condition, null, null, null, true);
for (GenericValue alias : pathAliases) {
alias.set("thruDate", now);
delegator.store(alias);
}
List<GenericValue> subContents = delegator.findList("ContentAssoc", condition, null, null, null, true);
for (GenericValue subContentAssoc : subContents) {
deleteWebPathAliases(delegator, subContentAssoc.getString("contentIdTo"));
}
}
private static Map<String, Object> getTreeNode(GenericValue assoc) throws GenericEntityException {
GenericValue content = assoc.getRelatedOne("ToContent", true);
String contentName = assoc.getString("contentIdTo");
if (content != null && content.getString("contentName") != null) {
contentName = content.getString("contentName");
if (contentName.length() > CONTENT_NAME_MAX_LENGTH) {
contentName = contentName.substring(0, CONTENT_NAME_MAX_LENGTH);
}
}
Map<String, Object> data = UtilMisc.toMap(
"title", (Object) contentName
);
Map<String, Object> attr = UtilMisc.toMap(
"id", assoc.get("contentIdTo"),
"contentId", assoc.get("contentId"),
"fromDate", assoc.getTimestamp("fromDate").toString(),
"contentAssocTypeId", assoc.get("contentAssocTypeId")
);
Map<String, Object> node = UtilMisc.toMap("data", (Object) data, "attr", (Object) attr);
List<GenericValue> assocChildren = content.getRelated("FromContentAssoc", null, null, true);
assocChildren = EntityUtil.filterByDate(assocChildren);
if (!CollectionUtils.isEmpty(assocChildren)) {
node.put("state", "closed");
}
return node;
}
}
@@ -0,0 +1,284 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.compdoc;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilFormatOut;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceAuthException;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.webapp.event.CoreEvents;
import org.ofbiz.webapp.website.WebSiteWorker;
/**
* CompDocEvents Class
*/
public class CompDocEvents {
public static final String module = CompDocEvents.class.getName();
/**
*
* @param request
* @param response
* @return
*
* Creates the topmost Content entity of a Composite Document tree.
* Also creates an "empty" Composite Document Instance Content entity.
* Creates ContentRevision/Item records for each, as well.
*/
public static String persistRootCompDoc(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
Delegator delegator = (Delegator)request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher)request.getAttribute("dispatcher");
Locale locale = UtilHttp.getLocale(request);
HttpSession session = request.getSession();
//Security security = (Security)request.getAttribute("security");
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
String contentId = (String)paramMap.get("contentId");
//String instanceContentId = null;
if (UtilValidate.isNotEmpty(contentId)) {
try {
EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Error running serviceName persistContentAndAssoc", module);
String errMsg = UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale);
request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + " [" + "persistContentAndAssoc" + "]: " + e.toString());
return "error";
}
}
ModelService modelService = null;
try {
modelService = dispatcher.getDispatchContext().getModelService("persistContentAndAssoc");
} catch (GenericServiceException e) {
String errMsg = "Error getting model service for serviceName, 'persistContentAndAssoc'. " + e.toString();
Debug.logError(errMsg, module);
request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "</li>");
return "error";
}
Map<String, Object> persistMap = modelService.makeValid(paramMap, ModelService.IN_PARAM);
persistMap.put("userLogin", userLogin);
try {
Map<String, Object> persistResult = dispatcher.runSync("persistContentAndAssoc", persistMap);
contentId = (String)persistResult.get("contentId");
//request.setAttribute("contentId", contentId);
for (Object obj : persistResult.keySet()) {
Object val = persistResult.get(obj);
request.setAttribute(obj.toString(), val);
}
// Update ContentRevision and ContentRevisonItem
Map<String, Object> contentRevisionMap = new HashMap<String, Object>();
contentRevisionMap.put("itemContentId", contentId);
contentRevisionMap.put("contentId", contentId);
contentRevisionMap.put("userLogin", userLogin);
Map<String, Object> result = dispatcher.runSync("persistContentRevisionAndItem", contentRevisionMap);
for (Object obj : result.keySet()) {
Object val = result.get(obj);
request.setAttribute(obj.toString(), val);
}
String errorMsg = ServiceUtil.getErrorMessage(result);
if (UtilValidate.isNotEmpty(errorMsg)) {
String errMsg = "Error running serviceName, 'persistContentRevisionAndItem'. " + errorMsg;
Debug.logError(errMsg, module);
request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "</li>");
return "error";
}
} catch (GenericServiceException e) {
String errMsg = "Error running serviceName, 'persistContentAndAssoc'. " + e.toString();
Debug.logError(errMsg, module);
request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "</li>");
return "error";
}
return "success";
}
public static String padNumberWithLeadingZeros(Long num, Integer padLen) {
String s = UtilFormatOut.formatPaddedNumber(num.longValue(), padLen.intValue());
return s;
}
public static String genCompDocPdf(HttpServletRequest request, HttpServletResponse response) {
String responseStr = "success";
//ByteBuffer byteBuffer = null;
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
ServletContext servletContext = session.getServletContext();
LocalDispatcher dispatcher = (LocalDispatcher)request.getAttribute("dispatcher");
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String contentId = (String)paramMap.get("contentId");
Locale locale = UtilHttp.getLocale(request);
String rootDir = null;
String webSiteId = WebSiteWorker.getWebSiteId(request);
String https = null;
if (UtilValidate.isEmpty(rootDir)) {
rootDir = servletContext.getRealPath("/");
}
if (UtilValidate.isEmpty(https)) {
https = (String) servletContext.getAttribute("https");
}
Map<String, Object> mapIn = new HashMap<String, Object>();
mapIn.put("contentId", contentId);
mapIn.put("locale", locale);
mapIn.put("rootDir", rootDir);
mapIn.put("webSiteId", webSiteId);
mapIn.put("https", https);
mapIn.put("userLogin", userLogin);
Map<String, Object> results = null;
try {
results = dispatcher.runSync("renderCompDocPdf", mapIn);
} catch (ServiceAuthException e) {
request.setAttribute("_ERROR_MESSAGE_", e.toString());
return "error";
} catch (GenericServiceException e) {
request.setAttribute("_ERROR_MESSAGE_", e.toString());
return "error";
} catch (Exception e) {
request.setAttribute("_ERROR_MESSAGE_", e.toString());
return "error";
}
if (ServiceUtil.isError(results)) {
request.setAttribute("_ERROR_MESSAGE_", ServiceUtil.getErrorMessage(results));
return "error";
}
ByteBuffer outByteBuffer = (ByteBuffer) results.get("outByteBuffer");
// setup content type
String contentType = "application/pdf; charset=ISO-8859-1";
ByteArrayInputStream bais = new ByteArrayInputStream(outByteBuffer.array());
/*
try {
FileOutputStream fos = new FileOutputStream(FileUtil.getFile("/home/byersa/pdftest.pdf"));
fos.write(outByteBuffer.getBytes());
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
*/
try {
UtilHttp.streamContentToBrowser(response, bais, outByteBuffer.limit(), contentType);
} catch (IOException e) {
request.setAttribute("_ERROR_MESSAGE_", e.toString());
return "error";
}
return responseStr;
}
public static String genContentPdf(HttpServletRequest request, HttpServletResponse response) {
String responseStr = "success";
//ByteBuffer byteBuffer = null;
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
ServletContext servletContext = session.getServletContext();
LocalDispatcher dispatcher = (LocalDispatcher)request.getAttribute("dispatcher");
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String contentId = (String)paramMap.get("contentId");
Locale locale = UtilHttp.getLocale(request);
String rootDir = null;
String webSiteId = WebSiteWorker.getWebSiteId(request);
String https = null;
if (UtilValidate.isEmpty(rootDir)) {
rootDir = servletContext.getRealPath("/");
}
if (UtilValidate.isEmpty(https)) {
https = (String) servletContext.getAttribute("https");
}
Map<String, Object> mapIn = new HashMap<String, Object>();
mapIn.put("contentId", contentId);
mapIn.put("locale", locale);
mapIn.put("rootDir", rootDir);
mapIn.put("webSiteId", webSiteId);
mapIn.put("https", https);
mapIn.put("userLogin", userLogin);
Map<String, Object> results = null;
try {
results = dispatcher.runSync("renderContentPdf", mapIn);
} catch (ServiceAuthException e) {
request.setAttribute("_ERROR_MESSAGE_", e.toString());
return "error";
} catch (GenericServiceException e) {
request.setAttribute("_ERROR_MESSAGE_", e.toString());
return "error";
} catch (Exception e) {
request.setAttribute("_ERROR_MESSAGE_", e.toString());
return "error";
}
if (ServiceUtil.isError(results)) {
request.setAttribute("_ERROR_MESSAGE_", ServiceUtil.getErrorMessage(results));
return "error";
}
ByteBuffer outByteBuffer = (ByteBuffer) results.get("outByteBuffer");
// setup content type
String contentType = "application/pdf; charset=ISO-8859-1";
ByteArrayInputStream bais = new ByteArrayInputStream(outByteBuffer.array());
/*
try {
FileOutputStream fos = new FileOutputStream(FileUtil.getFile("/home/byersa/pdftest.pdf"));
fos.write(outByteBuffer.getBytes());
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
*/
try {
UtilHttp.streamContentToBrowser(response, bais, outByteBuffer.limit(), contentType);
} catch (IOException e) {
request.setAttribute("_ERROR_MESSAGE_", e.toString());
return "error";
}
return responseStr;
}
}
@@ -0,0 +1,408 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.compdoc;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.content.data.DataResourceWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.webapp.event.CoreEvents;
import org.ofbiz.webapp.view.ViewHandlerException;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
/**
* CompDocEvents Class
*/
public class CompDocServices {
public static final String module = CompDocServices.class.getName();
public static final String resource = "ContentUiLabels";
/**
*
* Creates the topmost Content entity of a Composite Document tree.
* Also creates an "empty" Composite Document Instance Content entity.
* Creates ContentRevision/Item records for each, as well.
* @param dctx the dispatch context
* @param context the context
* @return Creates the topmost Content entity of a Composite Document tree
*/
public static Map<String, Object> persistRootCompDoc(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<String, Object>();
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = (Locale)context.get("locale");
GenericValue userLogin = (GenericValue)context.get("userLogin");
String contentId = (String)context.get("contentId");
//String instanceContentId = null;
if (UtilValidate.isNotEmpty(contentId)) {
try {
EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Error running serviceName persistContentAndAssoc", module);
return ServiceUtil.returnError(UtilProperties.getMessage(CoreEvents.err_resource, "ContentNoContentFound", UtilMisc.toMap("contentId", contentId), locale));
}
}
ModelService modelService = null;
try {
modelService = dispatcher.getDispatchContext().getModelService("persistContentAndAssoc");
} catch (GenericServiceException e) {
Debug.logError("Error getting model service for serviceName, 'persistContentAndAssoc'. " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(CoreEvents.err_resource, "coreEvents.error_modelservice_for_srv_name", locale));
}
Map<String, Object> persistMap = modelService.makeValid(context, ModelService.IN_PARAM);
persistMap.put("userLogin", userLogin);
try {
Map<String, Object> persistContentResult = dispatcher.runSync("persistContentAndAssoc", persistMap);
if (ServiceUtil.isError(persistContentResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentContentCreatingError", UtilMisc.toMap("serviceName", "persistContentAndAssoc"), locale), null, null, persistContentResult);
}
contentId = (String) persistContentResult.get("contentId");
result.putAll(persistContentResult);
//request.setAttribute("contentId", contentId);
// Update ContentRevision and ContentRevisonItem
Map<String, Object> contentRevisionMap = new HashMap<String, Object>();
contentRevisionMap.put("itemContentId", contentId);
contentRevisionMap.put("contentId", contentId);
contentRevisionMap.put("userLogin", userLogin);
Map<String, Object> persistRevResult = dispatcher.runSync("persistContentRevisionAndItem", contentRevisionMap);
if (ServiceUtil.isError(persistRevResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentContentCreatingError", UtilMisc.toMap("serviceName", "persistContentRevisionAndItem"), locale), null, null, persistRevResult);
}
result.putAll(persistRevResult);
return result;
} catch (GenericServiceException e) {
Debug.logError(e, "Error running serviceName, 'persistContentAndAssoc'. " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentContentCreatingError", UtilMisc.toMap("serviceName", "persistContentAndAssoc"), locale) + e.toString());
}
}
public static Map<String, Object> renderCompDocPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Locale locale = (Locale) context.get("locale");
String rootDir = (String) context.get("rootDir");
String webSiteId = (String) context.get("webSiteId");
String https = (String) context.get("https");
Delegator delegator = dctx.getDelegator();
String contentId = (String) context.get("contentId");
String contentRevisionSeqId = (String) context.get("contentRevisionSeqId");
String oooHost = (String) context.get("oooHost");
String oooPort = (String) context.get("oooPort");
GenericValue userLogin = (GenericValue) context.get("userLogin");
try {
List<EntityCondition> exprList = new LinkedList<EntityCondition>();
exprList.add(EntityCondition.makeCondition("contentIdTo", EntityOperator.EQUALS, contentId));
exprList.add(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, "COMPDOC_PART"));
exprList.add(EntityCondition.makeCondition("rootRevisionContentId", EntityOperator.EQUALS, contentId));
if (UtilValidate.isNotEmpty(contentRevisionSeqId)) {
exprList.add(EntityCondition.makeCondition("contentRevisionSeqId", EntityOperator.LESS_THAN_EQUAL_TO, contentRevisionSeqId));
}
List<GenericValue> compDocParts = EntityQuery.use(delegator)
.select("rootRevisionContentId", "itemContentId", "maxRevisionSeqId", "contentId", "dataResourceId", "contentIdTo", "contentAssocTypeId", "fromDate", "sequenceNum")
.from("ContentAssocRevisionItemView")
.where(exprList)
.orderBy("sequenceNum").filterByDate().queryList();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
document.setPageSize(PageSize.LETTER);
//Rectangle rect = document.getPageSize();
//PdfWriter writer = PdfWriter.getInstance(document, baos);
PdfCopy writer = new PdfCopy(document, baos);
document.open();
int pgCnt = 0;
for (GenericValue contentAssocRevisionItemView : compDocParts) {
//String thisContentId = contentAssocRevisionItemView.getString("contentId");
//String thisContentRevisionSeqId = contentAssocRevisionItemView.getString("maxRevisionSeqId");
String thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId");
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", thisDataResourceId).queryOne();
String inputMimeType = null;
if (dataResource != null) {
inputMimeType = dataResource.getString("mimeTypeId");
}
byte [] inputByteArray = null;
PdfReader reader = null;
if (inputMimeType != null && inputMimeType.equals("application/pdf")) {
ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
inputByteArray = byteBuffer.array();
reader = new PdfReader(inputByteArray);
} else if (inputMimeType != null && inputMimeType.equals("text/html")) {
ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
inputByteArray = byteBuffer.array();
String s = new String(inputByteArray);
Debug.logInfo("text/html string:" + s, module);
continue;
} else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) {
String surveyResponseId = dataResource.getString("relatedDetailId");
String surveyId = null;
String acroFormContentId = null;
GenericValue surveyResponse = null;
if (UtilValidate.isNotEmpty(surveyResponseId)) {
surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
if (surveyResponse != null) {
surveyId = surveyResponse.getString("surveyId");
}
}
if (UtilValidate.isNotEmpty(surveyId)) {
GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
if (survey != null) {
acroFormContentId = survey.getString("acroFormContentId");
if (UtilValidate.isNotEmpty(acroFormContentId)) {
// TODO: is something supposed to be done here?
}
}
}
if (surveyResponse != null) {
if (UtilValidate.isEmpty(acroFormContentId)) {
// Create AcroForm PDF
Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyId));
if (ServiceUtil.isError(survey2PdfResults)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults);
}
ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer");
inputByteArray = outByteBuffer.array();
reader = new PdfReader(inputByteArray);
} else {
// Fill in acroForm
Map<String, Object> survey2AcroFieldResults = dispatcher.runSync("setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
if (ServiceUtil.isError(survey2AcroFieldResults)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorSettingAcroFields", locale), null, null, survey2AcroFieldResults);
}
ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer");
inputByteArray = outByteBuffer.array();
reader = new PdfReader(inputByteArray);
}
}
} else {
ByteBuffer inByteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir);
Map<String, Object> convertInMap = UtilMisc.<String, Object>toMap("userLogin", userLogin, "inByteBuffer", inByteBuffer, "inputMimeType", inputMimeType, "outputMimeType", "application/pdf");
if (UtilValidate.isNotEmpty(oooHost)) convertInMap.put("oooHost", oooHost);
if (UtilValidate.isNotEmpty(oooPort)) convertInMap.put("oooPort", oooPort);
Map<String, Object> convertResult = dispatcher.runSync("convertDocumentByteBuffer", convertInMap);
if (ServiceUtil.isError(convertResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentConvertingDocumentByteBuffer", locale), null, null, convertResult);
}
ByteBuffer outByteBuffer = (ByteBuffer) convertResult.get("outByteBuffer");
inputByteArray = outByteBuffer.array();
reader = new PdfReader(inputByteArray);
}
if (reader != null) {
int n = reader.getNumberOfPages();
for (int i=0; i < n; i++) {
PdfImportedPage pg = writer.getImportedPage(reader, i + 1);
//cb.addTemplate(pg, left, height * pgCnt);
writer.addPage(pg);
pgCnt++;
}
}
}
document.close();
ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("outByteBuffer", outByteBuffer);
return results;
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.toString());
} catch (IOException e) {
Debug.logError(e, "Error in CompDoc operation: ", module);
return ServiceUtil.returnError(e.toString());
} catch (Exception e) {
Debug.logError(e, "Error in CompDoc operation: ", module);
return ServiceUtil.returnError(e.toString());
}
}
public static Map<String, Object> renderContentPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Map<String, Object> results = ServiceUtil.returnSuccess();
String dataResourceId = null;
Locale locale = (Locale) context.get("locale");
String rootDir = (String) context.get("rootDir");
String webSiteId = (String) context.get("webSiteId");
String https = (String) context.get("https");
Delegator delegator = dctx.getDelegator();
String contentId = (String) context.get("contentId");
String contentRevisionSeqId = (String) context.get("contentRevisionSeqId");
String oooHost = (String) context.get("oooHost");
String oooPort = (String) context.get("oooPort");
GenericValue userLogin = (GenericValue) context.get("userLogin");
try {
//Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
//ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
document.setPageSize(PageSize.LETTER);
//Rectangle rect = document.getPageSize();
//PdfCopy writer = new PdfCopy(document, baos);
document.open();
GenericValue dataResource = null;
if (UtilValidate.isEmpty(contentRevisionSeqId)) {
GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
dataResourceId = content.getString("dataResourceId");
Debug.logInfo("SCVH(0b)- dataResourceId:" + dataResourceId, module);
dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
} else {
GenericValue contentRevisionItem = EntityQuery.use(delegator).from("ContentRevisionItem").where("contentId", contentId, "itemContentId", contentId, "contentRevisionSeqId", contentRevisionSeqId).cache().queryOne();
if (contentRevisionItem == null) {
throw new ViewHandlerException("ContentRevisionItem record not found for contentId=" + contentId
+ ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId);
}
Debug.logInfo("SCVH(1)- contentRevisionItem:" + contentRevisionItem, module);
Debug.logInfo("SCVH(2)-contentId=" + contentId
+ ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId, module);
dataResourceId = contentRevisionItem.getString("newDataResourceId");
Debug.logInfo("SCVH(3)- dataResourceId:" + dataResourceId, module);
dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
}
String inputMimeType = null;
if (dataResource != null) {
inputMimeType = dataResource.getString("mimeTypeId");
}
byte [] inputByteArray = null;
if (inputMimeType != null && inputMimeType.equals("application/pdf")) {
ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https, webSiteId, locale, rootDir);
inputByteArray = byteBuffer.array();
} else if (inputMimeType != null && inputMimeType.equals("text/html")) {
ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https, webSiteId, locale, rootDir);
inputByteArray = byteBuffer.array();
String s = new String(inputByteArray);
Debug.logInfo("text/html string:" + s, module);
} else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) {
String surveyResponseId = dataResource.getString("relatedDetailId");
String surveyId = null;
String acroFormContentId = null;
GenericValue surveyResponse = null;
if (UtilValidate.isNotEmpty(surveyResponseId)) {
surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
if (surveyResponse != null) {
surveyId = surveyResponse.getString("surveyId");
}
}
if (UtilValidate.isNotEmpty(surveyId)) {
GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
if (survey != null) {
acroFormContentId = survey.getString("acroFormContentId");
if (UtilValidate.isNotEmpty(acroFormContentId)) {
// TODO: is something supposed to be done here?
}
}
}
if (surveyResponse != null) {
if (UtilValidate.isEmpty(acroFormContentId)) {
// Create AcroForm PDF
Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
if (ServiceUtil.isError(survey2PdfResults)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults);
}
ByteBuffer outByteBuffer = (ByteBuffer)survey2PdfResults.get("outByteBuffer");
inputByteArray = outByteBuffer.array();
} else {
// Fill in acroForm
Map<String, Object> survey2AcroFieldResults = dispatcher.runSync("setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId));
if (ServiceUtil.isError(survey2AcroFieldResults)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorSettingAcroFields", locale), null, null, survey2AcroFieldResults);
}
ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer");
inputByteArray = outByteBuffer.array();
}
}
} else {
ByteBuffer inByteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https, webSiteId, locale, rootDir);
Map<String, Object> convertInMap = UtilMisc.<String, Object>toMap("userLogin", userLogin, "inByteBuffer", inByteBuffer,
"inputMimeType", inputMimeType, "outputMimeType", "application/pdf");
if (UtilValidate.isNotEmpty(oooHost)) convertInMap.put("oooHost", oooHost);
if (UtilValidate.isNotEmpty(oooPort)) convertInMap.put("oooPort", oooPort);
Map<String, Object> convertResult = dispatcher.runSync("convertDocumentByteBuffer", convertInMap);
if (ServiceUtil.isError(convertResult)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentConvertingDocumentByteBuffer", locale), null, null, convertResult);
}
ByteBuffer outByteBuffer = (ByteBuffer) convertResult.get("outByteBuffer");
inputByteArray = outByteBuffer.array();
}
ByteBuffer outByteBuffer = ByteBuffer.wrap(inputByteArray);
results.put("outByteBuffer", outByteBuffer);
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.toString());
} catch (IOException e) {
Debug.logError(e, "Error in PDF generation: ", module);
return ServiceUtil.returnError(e.toString());
} catch (Exception e) {
Debug.logError(e, "Error in PDF generation: ", module);
return ServiceUtil.returnError(e.toString());
}
return results;
}
}
@@ -0,0 +1,156 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.transaction.TransactionUtil;
import org.ofbiz.entity.util.EntityListIterator;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.content.content.ContentKeywordIndex;
import org.ofbiz.security.Security;
/**
* ContentEvents Class
*/
public class ContentEvents {
public static final String module = ContentEvents.class.getName();
public static final String resource = "ContentErrorUiLabels";
/**
* Updates/adds keywords for all contents
*
* @param request HTTPRequest object for the current request
* @param response HTTPResponse object for the current request
* @return String specifying the exit status of this event
*/
public static String updateAllContentKeywords(HttpServletRequest request, HttpServletResponse response) {
//String errMsg = "";
Delegator delegator = (Delegator) request.getAttribute("delegator");
Security security = (Security) request.getAttribute("security");
String updateMode = "CREATE";
String errMsg=null;
String doAll = request.getParameter("doAll");
// check permissions before moving on...
if (!security.hasEntityPermission("CONTENTMGR", "_" + updateMode, request.getSession())) {
Map<String, String> messageMap = UtilMisc.toMap("updateMode", updateMode);
errMsg = UtilProperties.getMessage(resource,"contentevents.not_sufficient_permissions", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
EntityListIterator entityListIterator = null;
int numConts = 0;
int errConts = 0;
boolean beganTx = false;
try {
// begin the transaction
beganTx = TransactionUtil.begin(7200);
try {
EntityQuery contentQuery = EntityQuery.use(delegator).from("Content");
if (Debug.infoOn()) {
long count = contentQuery.queryCount();
Debug.logInfo("========== Found " + count + " contents to index ==========", module);
}
entityListIterator = contentQuery.queryIterator();
} catch (GenericEntityException gee) {
Debug.logWarning(gee, gee.getMessage(), module);
Map<String, String> messageMap = UtilMisc.toMap("gee", gee.toString());
errMsg = UtilProperties.getMessage(resource,"contentevents.error_getting_content_list", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_ERROR_MESSAGE_", errMsg);
throw gee;
}
GenericValue content;
while ((content = entityListIterator.next()) != null) {
try {
ContentKeywordIndex.indexKeywords(content, "Y".equals(doAll));
} catch (GenericEntityException e) {
//request.setAttribute("_ERROR_MESSAGE_", errMsg);
Debug.logWarning("[ContentEvents.updateAllContentKeywords] Could not create content-keyword (write error); message: " + e.getMessage(), module);
errConts++;
}
numConts++;
if (numConts % 500 == 0) {
Debug.logInfo("Keywords indexed for " + numConts + " so far", module);
}
}
} catch (GenericEntityException e) {
try {
TransactionUtil.rollback(beganTx, e.getMessage(), e);
} catch (Exception e1) {
Debug.logError(e1, module);
}
return "error";
} catch (Throwable t) {
Debug.logError(t, module);
request.setAttribute("_ERROR_MESSAGE_", t.getMessage());
try {
TransactionUtil.rollback(beganTx, t.getMessage(), t);
} catch (Exception e2) {
Debug.logError(e2, module);
}
return "error";
} finally {
if (entityListIterator != null) {
try {
entityListIterator.close();
} catch (GenericEntityException gee) {
Debug.logError(gee, "Error closing EntityListIterator when indexing content keywords.", module);
}
}
// commit the transaction
try {
TransactionUtil.commit(beganTx);
} catch (Exception e) {
Debug.logError(e, module);
}
}
if (errConts == 0) {
Map<String, String> messageMap = UtilMisc.toMap("numConts", Integer.toString(numConts));
errMsg = UtilProperties.getMessage(resource,"contentevents.keyword_creation_complete_for_contents", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_EVENT_MESSAGE_", errMsg);
return "success";
} else {
Map<String, String> messageMap = UtilMisc.toMap("numConts", Integer.toString(numConts));
messageMap.put("errConts", Integer.toString(errConts));
errMsg = UtilProperties.getMessage(resource,"contentevents.keyword_creation_complete_for_contents_with_errors", messageMap, UtilHttp.getLocale(request));
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
}
}
@@ -0,0 +1,242 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.common.KeywordSearchUtil;
import org.ofbiz.content.data.DataResourceWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtilProperties;
/**
* Does indexing in preparation for a keyword search.
*/
public class ContentKeywordIndex {
public static final String module = ContentKeywordIndex.class.getName();
public static void forceIndexKeywords(GenericValue content) throws GenericEntityException {
ContentKeywordIndex.indexKeywords(content, true);
}
public static void indexKeywords(GenericValue content) throws GenericEntityException {
ContentKeywordIndex.indexKeywords(content, false);
}
public static void indexKeywords(GenericValue content, boolean doAll) throws GenericEntityException {
if (content == null) return;
Delegator delegator = content.getDelegator();
if (delegator == null) return;
String contentId = content.getString("contentId");
// get these in advance just once since they will be used many times for the multiple strings to index
String separators = KeywordSearchUtil.getSeparators();
String stopWordBagOr = KeywordSearchUtil.getStopWordBagOr();
String stopWordBagAnd = KeywordSearchUtil.getStopWordBagAnd();
boolean removeStems = KeywordSearchUtil.getRemoveStems();
Set<String> stemSet = KeywordSearchUtil.getStemSet();
Map<String, Long> keywords = new TreeMap<String, Long>();
List<String> strings = new LinkedList<String>();
int pidWeight = 1;
keywords.put(content.getString("contentId").toLowerCase(), Long.valueOf(pidWeight));
addWeightedKeywordSourceString(content, "dataResourceId", strings);
addWeightedKeywordSourceString(content, "contentName", strings);
addWeightedKeywordSourceString(content, "description", strings);
// ContentAttribute
List<GenericValue> contentAttributes = EntityQuery.use(delegator).from("ContentAttribute").where("contentId", contentId).queryList();
for (GenericValue contentAttribute: contentAttributes) {
addWeightedKeywordSourceString(contentAttribute, "attrName", strings);
addWeightedKeywordSourceString(contentAttribute, "attrValue", strings);
}
// ContentMetaData
List<GenericValue> contentMetaDatas = EntityQuery.use(delegator).from("ContentMetaData").where("contentId", contentId).queryList();
for (GenericValue contentMetaData: contentMetaDatas) {
addWeightedKeywordSourceString(contentMetaData, "metaDataValue", strings);
}
// ContentRole
List<GenericValue> contentRoles = EntityQuery.use(delegator).from("ContentRole").where("contentId", contentId).queryList();
for (GenericValue contentRole: contentRoles) {
GenericValue party = EntityQuery.use(delegator).from("PartyNameView").where("partyId", contentRole.get("partyId")).queryOne();
if (party != null) {
addWeightedKeywordSourceString(party, "description", strings);
addWeightedKeywordSourceString(party, "firstName", strings);
addWeightedKeywordSourceString(party, "middleName", strings);
addWeightedKeywordSourceString(party, "lastName", strings);
addWeightedKeywordSourceString(party, "groupName", strings);
}
}
// DataResourceRole
List<GenericValue> dataResourceRoles = EntityQuery.use(delegator).from("DataResourceRole").where("dataResourceId", content.get("dataResourceId")).queryList();
for (GenericValue dataResourceRole: dataResourceRoles) {
GenericValue party = EntityQuery.use(delegator).from("PartyNameView").where("partyId", dataResourceRole.get("partyId")).queryOne();
if (party != null) {
addWeightedKeywordSourceString(party, "description", strings);
addWeightedKeywordSourceString(party, "firstName", strings);
addWeightedKeywordSourceString(party, "middleName", strings);
addWeightedKeywordSourceString(party, "lastName", strings);
addWeightedKeywordSourceString(party, "groupName", strings);
}
}
// Product
List<GenericValue> productContentList = EntityQuery.use(delegator).from("ProductContent").where("contentId", contentId).queryList();
for (GenericValue productContent: productContentList) {
GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productContent.get("productId")).queryOne();
if (product != null) {
addWeightedKeywordSourceString(product, "productName", strings);
addWeightedKeywordSourceString(product, "internalName", strings);
addWeightedKeywordSourceString(product, "brandName", strings);
addWeightedKeywordSourceString(product, "description", strings);
addWeightedKeywordSourceString(product, "longDescription", strings);
}
}
// ProductCategory
List<GenericValue> productCategoryContentList = EntityQuery.use(delegator).from("ProductCategoryContent").where("contentId", contentId).queryList();
for (GenericValue productCategoryContent: productCategoryContentList) {
GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", productCategoryContent.getString("productCategoryId")).queryOne();
if (productCategory != null) {
addWeightedKeywordSourceString(productCategory, "categoryName", strings);
addWeightedKeywordSourceString(productCategory, "description", strings);
addWeightedKeywordSourceString(productCategory, "longDescription", strings);
}
}
// PartyContent
List<GenericValue> partyContents = EntityQuery.use(delegator).from("PartyContent").where("contentId", contentId).queryList();
for (GenericValue partyContent: partyContents) {
GenericValue party = EntityQuery.use(delegator).from("PartyNameView").where("partyId", partyContent.get("partyId")).queryOne();
if (party != null) {
addWeightedKeywordSourceString(party, "description", strings);
addWeightedKeywordSourceString(party, "firstName", strings);
addWeightedKeywordSourceString(party, "middleName", strings);
addWeightedKeywordSourceString(party, "lastName", strings);
addWeightedKeywordSourceString(party, "groupName", strings);
}
}
// WebSiteContent
List<GenericValue> webSiteContents = EntityQuery.use(delegator).from("WebSiteContent").where("contentId", contentId).queryList();
for (GenericValue webSiteContent: webSiteContents) {
GenericValue webSite = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteContent.get("webSiteId")).queryOne();
if (webSite != null) {
addWeightedKeywordSourceString(webSite, "siteName", strings);
addWeightedKeywordSourceString(webSite, "httpHost", strings);
addWeightedKeywordSourceString(webSite, "httpsHost", strings);
}
}
// WorkEffortContent
List<GenericValue> workEffortContents = EntityQuery.use(delegator).from("WorkEffortContent").where("contentId", contentId).queryList();
for (GenericValue workEffortContent: workEffortContents) {
GenericValue workEffort = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", workEffortContent.get("workEffortId")).queryOne();
if (workEffort != null) {
addWeightedKeywordSourceString(workEffort, "workEffortName", strings);
}
}
// DataResource
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", content.get("dataResourceId")).queryOne();
if (dataResource != null) {
addWeightedKeywordSourceString(dataResource, "dataResourceName", strings);
addWeightedKeywordSourceString(dataResource, "objectInfo", strings);
}
/*List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator).from("ContentDataResourceView").where("contentId", contentId).queryList();
for (GenericValue contentDataResourceView: contentDataResourceViews) {
int weight = 1;
addWeightedDataResourceString(contentDataResourceView, weight, strings, delegator, content);
List<GenericValue> alternateViews = contentDataResourceView.getRelated("ContentAssocDataResourceViewTo", UtilMisc.toMap("caContentAssocTypeId", "ALTERNATE_LOCALE"), UtilMisc.toList("-caFromDate"), false);
alternateViews = EntityUtil.filterByDate(alternateViews, UtilDateTime.nowTimestamp(), "caFromDate", "caThruDate", true);
for (GenericValue thisView: alternateViews) {
addWeightedDataResourceString(thisView, weight, strings, delegator, content);
}
}*/
if (UtilValidate.isNotEmpty(strings)) {
for (String str: strings) {
// call process keywords method here
KeywordSearchUtil.processKeywordsForIndex(str, keywords, separators, stopWordBagAnd, stopWordBagOr, removeStems, stemSet);
}
}
List<GenericValue> toBeStored = new LinkedList<GenericValue>();
int keywordMaxLength = EntityUtilProperties.getPropertyAsInteger("contentsearch", "content.keyword.max.length", 0).intValue();
for (Map.Entry<String, Long> entry: keywords.entrySet()) {
if (entry.getKey().length() <= keywordMaxLength) {
GenericValue contentKeyword = delegator.makeValue("ContentKeyword", UtilMisc.toMap("contentId", content.getString("contentId"), "keyword", entry.getKey(), "relevancyWeight", entry.getValue()));
toBeStored.add(contentKeyword);
}
}
if (toBeStored.size() > 0) {
if (Debug.verboseOn()) Debug.logVerbose("[ContentKeywordIndex.indexKeywords] Storing " + toBeStored.size() + " keywords for contentId " + content.getString("contentId"), module);
if ("true".equals(EntityUtilProperties.getPropertyValue("contentsearch", "index.delete.on_index", "false", delegator))) {
// delete all keywords if the properties file says to
delegator.removeByAnd("ContentKeyword", UtilMisc.toMap("contentId", content.getString("contentId")));
}
delegator.storeAll(toBeStored);
}
}
public static void addWeightedDataResourceString(GenericValue drView, int weight, List<String> strings, Delegator delegator, GenericValue content) {
Map<String, Object> drContext = UtilMisc.<String, Object>toMap("content", content);
try {
String contentText = DataResourceWorker.renderDataResourceAsText(delegator, drView.getString("dataResourceId"), drContext, null, null, false);
for (int i = 0; i < weight; i++) {
strings.add(contentText);
}
} catch (IOException e1) {
Debug.logError(e1, "Error getting content text to index", module);
} catch (GeneralException e1) {
Debug.logError(e1, "Error getting content text to index", module);
}
}
public static void addWeightedKeywordSourceString(GenericValue value, String fieldName, List<String> strings) {
if (value.getString(fieldName) != null) {
int weight = 1;
for (int i = 0; i < weight; i++) {
strings.add(value.getString(fieldName));
}
}
}
}
@@ -0,0 +1,551 @@
/*
k Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.ofbiz.content.content;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.content.data.DataResourceWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.webapp.control.RequestHandler;
import org.ofbiz.webapp.website.WebSiteWorker;
/**
* ContentMapFacade
*/
public class ContentMapFacade implements Map<Object, Object> {
public static final String module = ContentMapFacade.class.getName();
protected static final Set<String> mapKeySet = new HashSet<String>();
static {
mapKeySet.add("fields");
mapKeySet.add("link");
mapKeySet.add("data");
mapKeySet.add("dataresource");
mapKeySet.add("subcontent");
mapKeySet.add("subcontent_all");
mapKeySet.add("metadata");
mapKeySet.add("content");
mapKeySet.add("render");
}
protected final LocalDispatcher dispatcher;
protected final Delegator delegator;
protected final String contentId;
protected final GenericValue value;
protected final Map<String, Object> context;
protected final Locale locale;
protected final String mimeType;
protected final boolean cache;
protected boolean allowRender = true;
protected boolean isDecorated = false;
protected ContentMapFacade decoratedContent = null;
// internal objects
private String sortOrder="-fromDate";
private String mapKeyFilter="";
private String statusFilter="";
private DataResource dataResource;
private SubContent subContent;
private MetaData metaData;
private Content content;
private GenericValue fields = null;
public ContentMapFacade(LocalDispatcher dispatcher, GenericValue content, Map<String, Object> context, Locale locale, String mimeTypeId, boolean cache) {
this.dispatcher = dispatcher;
this.value = content;
this.context = context;
this.locale = locale;
this.mimeType = mimeTypeId;
this.cache = cache;
this.contentId = content.getString("contentId");
this.delegator = content.getDelegator();
this.allowRender = false;
init();
}
private ContentMapFacade(LocalDispatcher dispatcher, Delegator delegator, String contentId, Map<String, Object> context, Locale locale, String mimeTypeId, boolean cache) {
this.dispatcher = dispatcher;
this.delegator = delegator;
this.contentId = contentId;
this.context = context;
this.locale = locale;
this.mimeType = mimeTypeId;
this.cache = cache;
try {
if (cache) {
this.value = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
} else {
this.value = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
throw new RuntimeException(e.getMessage());
}
init();
}
private void init() {
this.dataResource = new DataResource();
this.subContent = new SubContent();
this.metaData = new MetaData();
this.content = new Content();
}
public void setRenderFlag(boolean render) {
this.allowRender = render;
}
public void setIsDecorated(boolean isDecorated) {
this.isDecorated = isDecorated;
}
// interface methods
public int size() {
return 1;
}
public boolean isEmpty() {
return false;
}
public boolean containsKey(Object object) {
return false;
}
public boolean containsValue(Object object) {
return false;
}
public Object put(Object name, Object value) {
Debug.logWarning("This [put()] method is not implemented in ContentMapFacade", module);
return null;
}
public Object remove(Object object) {
Debug.logWarning("This [remove()] method is not implemented in ContentMapFacade", module);
return null;
}
public void putAll(Map<?, ?> map) {
Debug.logWarning("This method [putAll()] is not implemented in ContentMapFacade", module);
}
public void clear() {
Debug.logWarning("This method [clear()] is not implemented in ContentMapFacade", module);
}
public Set<Object> keySet() {
// Debug.logWarning("This method [keySet()] is not completely implemented in ContentMapFacade", module);
return UtilGenerics.checkSet(mapKeySet);
}
public Collection<Object> values() {
Debug.logWarning("This method [values()] is not implemented in ContentMapFacade", module);
return null;
}
public Set<Map.Entry<Object, Object>> entrySet() {
Debug.logWarning("This method [entrySet()] is not implemented in ContentMapFacade", module);
return null;
}
public void setSortOrder(Object obj) {
if (!(obj instanceof String)) {
Debug.logWarning("sortOrder parameters must be a string", module);
return;
}
this.sortOrder=(String) obj;
this.subContent.setSortOrder(obj);
}
public void setMapKeyFilter(Object obj) {
if (!(obj instanceof String)) {
Debug.logWarning("mapKeyFilter parameters must be a string", module);
return;
}
this.mapKeyFilter=(String) obj;
}
public void setStatusFilter(Object obj) {
if (!(obj instanceof String)) {
Debug.logWarning("statusFilter parameters must be a string", module);
return;
}
this.statusFilter=(String) obj;
this.subContent.setStatusFilter(obj);
}
public void setDecoratedContent(ContentMapFacade decoratedContent) {
this.decoratedContent = decoratedContent;
}
// implemented get method
public Object get(Object obj) {
if (!(obj instanceof String)) {
Debug.logWarning("Key parameters must be a string", module);
return null;
}
String name = (String) obj;
if ("fields".equalsIgnoreCase(name)) {
// fields key, returns value object
if (this.fields != null) {
return fields;
}
try {
EntityQuery contentQuery = EntityQuery.use(delegator).from("Content").where("contentId", contentId);
if (cache) {
contentQuery.cache();
}
this.fields = contentQuery.queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return this.fields;
} else if ("link".equalsIgnoreCase(name)) {
// link to this content
RequestHandler rh = (RequestHandler) this.context.get("_REQUEST_HANDLER_");
HttpServletRequest request = (HttpServletRequest) this.context.get("request");
HttpServletResponse response = (HttpServletResponse) this.context.get("response");
if (rh != null && request != null && response != null) {
String webSiteId = WebSiteWorker.getWebSiteId(request);
Delegator delegator = (Delegator) request.getAttribute("delegator");
String contentUri = this.contentId;
// Try and find a WebSitePathAlias record to use, it isn't very feasible to find an alias by (parent)contentId/mapKey
// so we're only looking for a direct alias using contentId
if (webSiteId != null && delegator != null) {
try {
GenericValue webSitePathAlias = EntityQuery.use(delegator).from("WebSitePathAlias")
.where("mapKey", null,
"webSiteId", webSiteId,
"contentId", this.contentId)
.orderBy("-fromDate")
.cache().filterByDate().queryFirst();
if (webSitePathAlias != null) {
contentUri = webSitePathAlias.getString("pathAlias");
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
String contextLink = rh.makeLink(request, response, contentUri, true, false, true);
// Debug.logInfo("Made link to content with ID [" + this.contentId + "]: " + contextLink, module);
return contextLink;
} else {
return this.contentId;
}
} else if ("data".equalsIgnoreCase(name) || "dataresource".equalsIgnoreCase(name)) {
// data (resource) object
return dataResource;
} else if ("subcontent_all".equalsIgnoreCase(name)) {
// subcontent list of ordered subcontent
List<ContentMapFacade> subContent = new LinkedList<ContentMapFacade>();
List<GenericValue> subs = null;
try {
Map<String, Object> expressions = new HashMap<String, Object>();
expressions.put("contentIdStart", contentId);
if(!this.mapKeyFilter.equals("")) {
expressions.put("caMapKey", this.mapKeyFilter);
}
if(!this.statusFilter.equals("")) {
expressions.put("statusId", this.statusFilter);
}
subs = EntityQuery.use(delegator).from("ContentAssocViewTo")
.where(expressions)
.orderBy(this.sortOrder)
.filterByDate()
.cache(cache).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (subs != null) {
for (GenericValue v: subs) {
subContent.add(new ContentMapFacade(dispatcher, delegator, v.getString("contentId"), context, locale, mimeType, cache));
}
}
return subContent;
} else if ("subcontent".equalsIgnoreCase(name)) {
// return the subcontent object
return this.subContent;
} else if ("metadata".equalsIgnoreCase(name)) {
// return list of metaData by predicate ID
return this.metaData;
} else if ("content".equalsIgnoreCase(name)) {
// content; returns object from contentId
return content;
} else if ("render".equalsIgnoreCase(name)) {
// render this content
return this.renderThis();
}
return null;
}
protected String renderThis() {
if (!this.allowRender && !this.isDecorated) {
String errorMsg = "WARNING: Cannot render content being rendered! (Infinite Recursion NOT allowed!)";
Debug.logWarning(errorMsg, module);
return "=========> " + errorMsg + " <=========";
}
// TODO: change to use the MapStack instead of a cloned Map
Map<String, Object> renderCtx = new HashMap<String, Object>();
renderCtx.putAll(context);
if (this.decoratedContent != null) {
renderCtx.put("decoratedContent", decoratedContent);
}
if (this.isDecorated) {
renderCtx.put("_IS_DECORATED_", Boolean.TRUE);
}
try {
return ContentWorker.renderContentAsText(dispatcher, delegator, contentId, renderCtx, locale, mimeType, cache);
} catch (GeneralException e) {
Debug.logError(e, module);
return e.toString();
} catch (IOException e) {
Debug.logError(e, module);
return e.toString();
}
}
@Override
public String toString() {
return this.renderThis();
}
abstract class AbstractInfo implements Map<Object, Object> {
public int size() {
return 1;
}
public boolean isEmpty() {
return false;
}
public boolean containsKey(Object object) {
return false;
}
public boolean containsValue(Object object) {
return false;
}
public abstract Object get(Object object);
public Object put(Object name, Object value) {
Debug.logWarning("This [put()] method is not implemented in ContentMapFacade.AbstractInfo", module);
return null;
}
public Object remove(Object object) {
Debug.logWarning("This [remove()] method is not implemented in ContentMapFacade.AbstractInfo", module);
return null;
}
public void putAll(Map<?, ?> map) {
Debug.logWarning("This method [putAll()] is not implemented in ContentMapFacade.AbstractInfo", module);
}
public void clear() {
Debug.logWarning("This method [clear()] is not implemented in ContentMapFacade.AbstractInfo", module);
}
public Set<Object> keySet() {
Debug.logWarning("This method [keySet()] is not implemented in ContentMapFacade.AbstractInfo", module);
return null;
}
public Collection<Object> values() {
Debug.logWarning("This method [values()] is not implemented in ContentMapFacade.AbstractInfo", module);
return null;
}
public Set<Map.Entry<Object, Object>> entrySet() {
Debug.logWarning("This method [entrySet()] is not implemented in ContentMapFacade.AbstractInfo", module);
return null;
}
}
class Content extends AbstractInfo {
@Override
public Object get(Object key) {
if (!(key instanceof String)) {
Debug.logWarning("Key parameters must be a string", module);
return null;
}
String name = (String) key;
if (name.toLowerCase().startsWith("id_")) {
name = name.substring(3);
}
// look up the content ID (of name)
GenericValue content = null;
try {
if (cache) {
content = EntityQuery.use(delegator).from("Content").where("contentId", name).cache().queryOne();
} else {
content = EntityQuery.use(delegator).from("Content").where("contentId", name).queryOne();
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (content != null) {
return new ContentMapFacade(dispatcher, delegator, content.getString("contentId"), context, locale, mimeType, cache);
}
return null;
}
}
class SubContent extends AbstractInfo {
private String sortOrder="-fromDate";
private String statusFilter="";
@Override
public Object get(Object key) {
if (!(key instanceof String)) {
Debug.logWarning("Key parameters must be a string", module);
return null;
}
String name = (String) key;
if (name.toLowerCase().startsWith("id_")) {
name = name.substring(3);
}
// key is the mapKey
GenericValue sub = null;
try {
Map<String, Object> expressions = new HashMap<String, Object>();
expressions.put("contentIdStart", contentId);
expressions.put("caMapKey", name);
if(!this.statusFilter.equals("")) {
expressions.put("statusId", this.statusFilter);
}
sub = EntityQuery.use(delegator).from("ContentAssocViewTo")
.where(expressions)
.orderBy(this.sortOrder)
.cache(cache)
.filterByDate().queryFirst();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (sub != null) {
return new ContentMapFacade(dispatcher, delegator, sub.getString("contentId"), context, locale, mimeType, cache);
}
return null;
}
public void setSortOrder(Object obj) {
if (!(obj instanceof String)) {
Debug.logWarning("sortOrder parameters must be a string", module);
return;
}
this.sortOrder=(String) obj;
}
public void setStatusFilter(Object obj) {
if (!(obj instanceof String)) {
Debug.logWarning("statusFilter parameters must be a string", module);
return;
}
this.statusFilter=(String) obj;
}
}
class MetaData extends AbstractInfo {
@Override
public Object get(Object key) {
if (!(key instanceof String)) {
Debug.logWarning("Key parameters must be a string", module);
return null;
}
String name = (String) key;
List<GenericValue> metaData = null;
try {
metaData = EntityQuery.use(delegator).from("ContentMetaData")
.where("contentId", contentId, "metaDataPredicateId", name)
.cache(cache).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return metaData;
}
}
class DataResource extends AbstractInfo {
@Override
public Object get(Object key) {
if (!(key instanceof String)) {
Debug.logWarning("Key parameters must be a string", module);
return null;
}
String name = (String) key;
if ("fields".equalsIgnoreCase(name)) {
// get the data resource value object
GenericValue dr = null;
try {
dr = value.getRelatedOne("DataResource", cache);
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
return dr;
} else if ("render".equalsIgnoreCase(name)) {
// render just the dataresource
try {
return DataResourceWorker.renderDataResourceAsText(delegator, value.getString("dataResourceId"), context, locale, mimeType, cache);
} catch (GeneralException e) {
Debug.logError(e, module);
return e.toString();
} catch (IOException e) {
Debug.logError(e, module);
return e.toString();
}
}
return null;
}
}
}
@@ -0,0 +1,338 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entityext.permission.EntityPermissionChecker;
import org.ofbiz.security.Security;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceUtil;
/**
* ContentPermissionServices Class
*
* Services for granting operation permissions on Content entities in a data-driven manner.
*/
public class ContentPermissionServices {
public static final String module = ContentPermissionServices.class.getName();
public static final String resource = "ContentUiLabels";
public ContentPermissionServices() {}
/**
* checkContentPermission
*
*@param dctx The DispatchContext that this service is operating in
*@param context Map containing the input parameters
*@return Map with the result of the service, the output parameters
*
* This service goes thru a series of test to determine if the user has
* authority to performed anyone of the passed in target operations.
*
* It expects a Content entity in "currentContent"
* It expects a list of contentOperationIds in "targetOperationList" rather
* than a scalar because it is thought that sometimes more than one operation
* would fit the situation.
* Similarly, it expects a list of contentPurposeTypeIds in "contentPurposeList".
* Again, normally there will just be one, but it is possible that a Content
* entity could have multiple purposes associated with it.
* The userLogin GenericValue is also required.
* A list of roleTypeIds is also possible.
*
* The basic sequence of testing events is:
* First the ContentPurposeOperation table is checked to see if there are any
* entries with matching purposes (and operations) with no roleTypeId (ie. _NA_).
* This is done because it would be the most common scenario and is quick to check.
*
* Secondly, the CONTENTMGR permission is checked.
*
* Thirdly, the ContentPurposeOperation table is rechecked to see if there are
* any conditions with roleTypeIds that match associated ContentRoles tied to the
* user.
* If a Party of "PARTY_GROUP" type is found, the PartyRelationship table is checked
* to see if the current user is linked to that group.
*
* If no match is found to this point and the current Content entity has a value for
* ownerContentId, then the last step is recusively applied, using the ContentRoles
* associated with the ownerContent entity.
*/
public static Map<String, Object> checkContentPermission(DispatchContext dctx, Map<String, ? extends Object> context) {
Debug.logWarning(new Exception(), "This service has been depricated in favor of [genericContentPermission]", module);
Security security = dctx.getSecurity();
Delegator delegator = dctx.getDelegator();
//TODO this parameters is still not used but this service need to be replaced by genericContentPermission
// String statusId = (String) context.get("statusId");
//TODO this parameters is still not used but this service need to be replaced by genericContentPermission
// String privilegeEnumId = (String) context.get("privilegeEnumId");
GenericValue content = (GenericValue) context.get("currentContent");
Boolean bDisplayFailCond = (Boolean)context.get("displayFailCond");
boolean displayFailCond = false;
if (bDisplayFailCond != null && bDisplayFailCond.booleanValue()) {
displayFailCond = true;
}
Debug.logInfo("displayFailCond(0):" + displayFailCond, "");
Boolean bDisplayPassCond = (Boolean)context.get("displayPassCond");
boolean displayPassCond = false;
if (bDisplayPassCond != null && bDisplayPassCond.booleanValue()) {
displayPassCond = true;
}
Debug.logInfo("displayPassCond(0):" + displayPassCond, "");
Map<String, Object> results = new HashMap<String, Object>();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String partyId = (String) context.get("partyId");
if (UtilValidate.isEmpty(partyId)) {
String passedUserLoginId = (String)context.get("userLoginId");
if (UtilValidate.isNotEmpty(passedUserLoginId)) {
try {
userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", passedUserLoginId).cache().queryOne();
if (userLogin != null) {
partyId = userLogin.getString("partyId");
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
}
}
if (UtilValidate.isEmpty(partyId) && userLogin != null) {
partyId = userLogin.getString("partyId");
}
// Do entity permission check. This will pass users with administrative permissions.
boolean passed = false;
// I realized, belatedly, that I wanted to be able to pass parameters in as
// strings so this service could be used in an action event directly,
// so I had to write this code to handle both list and strings
List<String> passedPurposes = UtilGenerics.checkList(context.get("contentPurposeList"));
String contentPurposeString = (String) context.get("contentPurposeString");
//Debug.logInfo("contentPurposeString(b):" + contentPurposeString, "");
if (UtilValidate.isNotEmpty(contentPurposeString)) {
List<String> purposesFromString = StringUtil.split(contentPurposeString, "|");
if (passedPurposes == null) {
passedPurposes = new LinkedList<String>();
}
passedPurposes.addAll(purposesFromString);
}
EntityPermissionChecker.StdAuxiliaryValueGetter auxGetter = new EntityPermissionChecker.StdAuxiliaryValueGetter("ContentPurpose", "contentPurposeTypeId", "contentId");
// Sometimes permissions need to be checked before an entity is created, so
// there needs to be a method for setting a purpose list
auxGetter.setList(passedPurposes);
//Debug.logInfo("passedPurposes(b):" + passedPurposes, "");
List<String> targetOperations = UtilGenerics.checkList(context.get("targetOperationList"));
//Debug.logInfo("targetOperations(b):" + targetOperations, "");
String targetOperationString = (String) context.get("targetOperationString");
//Debug.logInfo("targetOperationString(b):" + targetOperationString, "");
if (UtilValidate.isNotEmpty(targetOperationString)) {
List<String> operationsFromString = StringUtil.split(targetOperationString, "|");
if (targetOperations == null) {
targetOperations = new LinkedList<String>();
}
targetOperations.addAll(operationsFromString);
}
//Debug.logInfo("targetOperations(c):" + targetOperations, "");
EntityPermissionChecker.StdPermissionConditionGetter permCondGetter = new EntityPermissionChecker.StdPermissionConditionGetter("ContentPurposeOperation", "contentOperationId", "roleTypeId", "statusId", "contentPurposeTypeId", "privilegeEnumId");
permCondGetter.setOperationList(targetOperations);
EntityPermissionChecker.StdRelatedRoleGetter roleGetter = new EntityPermissionChecker.StdRelatedRoleGetter("Content", "roleTypeId", "contentId", "partyId", "ownerContentId", "ContentRole");
//Debug.logInfo("targetOperations(b):" + targetOperations, "");
List<String> passedRoles = UtilGenerics.checkList(context.get("roleTypeList"));
if (passedRoles == null) passedRoles = new LinkedList<String>();
String roleTypeString = (String) context.get("roleTypeString");
if (UtilValidate.isNotEmpty(roleTypeString)) {
List<String> rolesFromString = StringUtil.split(roleTypeString, "|");
passedRoles.addAll(rolesFromString);
}
roleGetter.setList(passedRoles);
String entityAction = (String) context.get("entityOperation");
if (entityAction == null) entityAction = "_ADMIN";
if (userLogin != null && entityAction != null) {
passed = security.hasEntityPermission("CONTENTMGR", entityAction, userLogin);
}
StringBuilder errBuf = new StringBuilder();
String permissionStatus = null;
List<Object> entityIds = new LinkedList<Object>();
if (passed) {
results.put("permissionStatus", "granted");
permissionStatus = "granted";
if (displayPassCond) {
errBuf.append("\n hasEntityPermission(" + entityAction + "): PASSED");
}
} else {
if (displayFailCond) {
errBuf.append("\n hasEntityPermission(" + entityAction + "): FAILED");
}
if (content != null)
entityIds.add(content);
String quickCheckContentId = (String) context.get("quickCheckContentId");
if (UtilValidate.isNotEmpty(quickCheckContentId)) {
List<String> quickList = StringUtil.split(quickCheckContentId, "|");
if (UtilValidate.isNotEmpty(quickList)) entityIds.addAll(quickList);
}
try {
boolean check = EntityPermissionChecker.checkPermissionMethod(delegator, partyId, "Content", entityIds, auxGetter, roleGetter, permCondGetter);
if (check) {
results.put("permissionStatus", "granted");
} else {
results.put("permissionStatus", "rejected");
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
permissionStatus = (String)results.get("permissionStatus");
errBuf.append("\n permissionStatus:");
errBuf.append(permissionStatus);
}
if ((permissionStatus.equals("granted") && displayPassCond)
|| (permissionStatus.equals("rejected") && displayFailCond)) {
// Don't show this if passed on 'hasEntityPermission'
if (displayFailCond || displayPassCond) {
if (!passed) {
errBuf.append("\n targetOperations:");
errBuf.append(targetOperations);
String errMsg = permCondGetter.dumpAsText();
errBuf.append("\n");
errBuf.append(errMsg);
errBuf.append("\n partyId:");
errBuf.append(partyId);
errBuf.append("\n entityIds:");
errBuf.append(entityIds);
if (auxGetter != null) {
errBuf.append("\n auxList:");
errBuf.append(auxGetter.getList());
}
if (roleGetter != null) {
errBuf.append("\n roleList:");
errBuf.append(roleGetter.getList());
}
}
}
}
Debug.logInfo("displayPass/FailCond(0), errBuf:" + errBuf.toString(), "");
results.put(ModelService.ERROR_MESSAGE, errBuf.toString());
return results;
}
public static Map<String, Object> checkAssocPermission(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> results = new HashMap<String, Object>();
// Security security = dctx.getSecurity();
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
Boolean bDisplayFailCond = (Boolean)context.get("displayFailCond");
String contentIdFrom = (String) context.get("contentIdFrom");
String contentIdTo = (String) context.get("contentIdTo");
GenericValue userLogin = (GenericValue) context.get("userLogin");
String entityAction = (String) context.get("entityOperation");
Locale locale = (Locale) context.get("locale");
if (entityAction == null) entityAction = "_ADMIN";
String permissionStatus = null;
GenericValue contentTo = null;
GenericValue contentFrom = null;
try {
contentTo = EntityQuery.use(delegator).from("Content").where("contentId", contentIdTo).cache().queryOne();
contentFrom = EntityQuery.use(delegator).from("Content").where("contentId", contentIdFrom).cache().queryOne();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"ContentContentToOrFromErrorRetriving", locale));
}
if (contentTo == null || contentFrom == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"ContentContentToOrFromIsNull",
UtilMisc.toMap("contentTo", contentTo, "contentFrom", contentFrom), locale));
}
// boolean isMatch = false;
// boolean isMatchTo = false;
// boolean isMatchFrom = false;
Map<String, Object> permResults = new HashMap<String, Object>();
// Use the purposes from the from entity for both cases.
List<String> relatedPurposes = EntityPermissionChecker.getRelatedPurposes(contentFrom, null);
List<String> relatedPurposesTo = EntityPermissionChecker.getRelatedPurposes(contentTo, relatedPurposes);
Map<String, Object> serviceInMap = new HashMap<String, Object>();
serviceInMap.put("userLogin", userLogin);
serviceInMap.put("targetOperationList", UtilMisc.toList("CONTENT_LINK_TO"));
serviceInMap.put("contentPurposeList", relatedPurposesTo);
serviceInMap.put("currentContent", contentTo);
serviceInMap.put("displayFailCond", bDisplayFailCond);
try {
permResults = dispatcher.runSync("checkContentPermission", serviceInMap);
} catch (GenericServiceException e) {
Debug.logError(e, "Problem checking permissions", "ContentServices");
}
permissionStatus = (String)permResults.get("permissionStatus");
if (permissionStatus == null || !permissionStatus.equals("granted")) {
if (bDisplayFailCond != null && bDisplayFailCond.booleanValue()) {
String errMsg = (String)permResults.get(ModelService.ERROR_MESSAGE);
results.put(ModelService.ERROR_MESSAGE, errMsg);
}
return results;
}
serviceInMap.put("currentContent", contentFrom);
serviceInMap.put("targetOperationList", UtilMisc.toList("CONTENT_LINK_FROM"));
serviceInMap.put("contentPurposeList", relatedPurposes);
try {
permResults = dispatcher.runSync("checkContentPermission", serviceInMap);
} catch (GenericServiceException e) {
Debug.logError(e, "Problem checking permissions", "ContentServices");
}
permissionStatus = (String)permResults.get("permissionStatus");
if (permissionStatus != null && permissionStatus.equals("granted")) {
results.put("permissionStatus", "granted");
} else {
if (bDisplayFailCond != null && bDisplayFailCond.booleanValue()) {
String errMsg = (String)permResults.get(ModelService.ERROR_MESSAGE);
results.put(ModelService.ERROR_MESSAGE, errMsg);
}
}
return results;
}
}
@@ -0,0 +1,927 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.common.KeywordSearchUtil;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityConditionList;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.model.DynamicViewEntity;
import org.ofbiz.entity.model.ModelKeyMap;
import org.ofbiz.entity.model.ModelViewEntity.ComplexAlias;
import org.ofbiz.entity.model.ModelViewEntity.ComplexAliasField;
import org.ofbiz.entity.transaction.GenericTransactionException;
import org.ofbiz.entity.transaction.TransactionUtil;
import org.ofbiz.entity.util.EntityListIterator;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtil;
public class ContentSearch {
public static final String module = ContentSearch.class.getName();
public static final String resource = "ContentUiLabels";
public static ArrayList<String> searchContents(List<? extends ContentSearchConstraint> contentSearchConstraintList, ResultSortOrder resultSortOrder, Delegator delegator, String visitId) {
ContentSearchContext contentSearchContext = new ContentSearchContext(delegator, visitId);
contentSearchContext.addContentSearchConstraints(contentSearchConstraintList);
contentSearchContext.setResultSortOrder(resultSortOrder);
ArrayList<String> contentIds = contentSearchContext.doSearch();
return contentIds;
}
public static void getAllSubContentIds(String contentId, Set<String> contentIdSet, Delegator delegator, Timestamp nowTimestamp) {
if (nowTimestamp == null) {
nowTimestamp = UtilDateTime.nowTimestamp();
}
// first make sure the current id is in the Set
contentIdSet.add(contentId);
// now find all sub-categories, filtered by effective dates, and call this routine for them
try {
List<GenericValue> contentAssocList = EntityQuery.use(delegator).from("ContentAssoc").where("contentIdFrom", contentId).cache().queryList();
for (GenericValue contentAssoc: contentAssocList) {
String subContentId = contentAssoc.getString("contentIdTo");
if (contentIdSet.contains(subContentId)) {
// if this category has already been traversed, no use doing it again; this will also avoid infinite loops
continue;
}
// do the date filtering in the loop to avoid looping through the list twice
if (EntityUtil.isValueActive(contentAssoc, nowTimestamp)) {
getAllSubContentIds(subContentId, contentIdSet, delegator, nowTimestamp);
}
}
// Find Content where current contentId = contentParentId; only select minimal fields to keep the size low
List<GenericValue> childContentList = EntityQuery.use(delegator)
.select("contentId", "contentParentId").from("Content")
.where("contentParentId", contentId)
.cache().queryList();
for (GenericValue childContent: childContentList) {
String subContentId = childContent.getString("contentId");
if (contentIdSet.contains(subContentId)) {
// if this category has already been traversed, no use doing it again; this will also avoid infinite loops
continue;
}
// do the date filtering in the loop to avoid looping through the list twice
getAllSubContentIds(subContentId, contentIdSet, delegator, nowTimestamp);
}
} catch (GenericEntityException e) {
Debug.logError(e, "Error finding sub-categories for content search", module);
}
}
public static class ContentSearchContext {
public int index = 1;
public List<EntityCondition> entityConditionList = new LinkedList<EntityCondition>();
public List<String> orderByList = new LinkedList<String>();
public Set<String> fieldsToSelect = UtilMisc.toSet("contentId");
public DynamicViewEntity dynamicViewEntity = new DynamicViewEntity();
public boolean contentIdGroupBy = false;
public boolean includedKeywordSearch = false;
public Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
public List<Set<String>> keywordFixedOrSetAndList = new LinkedList<Set<String>>();
public Set<String> orKeywordFixedSet = new HashSet<String>();
public Set<String> andKeywordFixedSet = new HashSet<String>();
public List<GenericValue> contentSearchConstraintList = new LinkedList<GenericValue>();
public ResultSortOrder resultSortOrder = null;
public Integer resultOffset = null;
public Integer maxResults = null;
protected Delegator delegator = null;
protected String visitId = null;
protected Integer totalResults = null;
public ContentSearchContext(Delegator delegator, String visitId) {
this.delegator = delegator;
this.visitId = visitId;
dynamicViewEntity.addMemberEntity("CNT", "Content");
}
public Delegator getDelegator() {
return this.delegator;
}
public void addContentSearchConstraints(List<? extends ContentSearchConstraint> contentSearchConstraintList) {
// Go through the constraints and add them in
for (ContentSearchConstraint constraint: contentSearchConstraintList) {
constraint.addConstraint(this);
}
}
public void setResultSortOrder(ResultSortOrder resultSortOrder) {
this.resultSortOrder = resultSortOrder;
}
public void setResultOffset(Integer resultOffset) {
this.resultOffset = resultOffset;
}
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
public Integer getTotalResults() {
return this.totalResults;
}
public ArrayList<String> doSearch() {
long startMillis = System.currentTimeMillis();
// do the query
EntityListIterator eli = this.doQuery(delegator);
ArrayList<String> contentIds = this.makeContentIdList(eli);
if (eli != null) {
try {
eli.close();
} catch (GenericEntityException e) {
Debug.logError(e, "Error closing ContentSearch EntityListIterator");
}
}
long endMillis = System.currentTimeMillis();
double totalSeconds = ((double)endMillis - (double)startMillis)/1000.0;
// store info about results in the database, attached to the user's visitId, if specified
this.saveSearchResultInfo(Long.valueOf(contentIds.size()), Double.valueOf(totalSeconds));
return contentIds;
}
public void finishKeywordConstraints() {
if (orKeywordFixedSet.size() == 0 && andKeywordFixedSet.size() == 0 && keywordFixedOrSetAndList.size() == 0) {
return;
}
// we know we have a keyword search to do, so keep track of that now...
this.includedKeywordSearch = true;
// if there is anything in the orKeywordFixedSet add it to the keywordFixedOrSetAndList
if (orKeywordFixedSet.size() > 0) {
// put in keywordFixedOrSetAndList to process with other or lists where at least one is required
keywordFixedOrSetAndList.add(orKeywordFixedSet);
}
// remove all or sets from the or set and list where the or set is size 1 and put them in the and list
Iterator<Set<String>> keywordFixedOrSetAndTestIter = keywordFixedOrSetAndList.iterator();
while (keywordFixedOrSetAndTestIter.hasNext()) {
Set<String> keywordFixedOrSet = keywordFixedOrSetAndTestIter.next();
if (keywordFixedOrSet.size() == 0) {
keywordFixedOrSetAndTestIter.remove();
} else if (keywordFixedOrSet.size() == 1) {
// treat it as just another and
andKeywordFixedSet.add(keywordFixedOrSet.iterator().next());
keywordFixedOrSetAndTestIter.remove();
}
}
boolean doingBothAndOr = (keywordFixedOrSetAndList.size() > 1) || (keywordFixedOrSetAndList.size() > 0 && andKeywordFixedSet.size() > 0);
Debug.logInfo("Finished initial setup of keywords, doingBothAndOr=" + doingBothAndOr + ", andKeywordFixedSet=" + andKeywordFixedSet + "\n keywordFixedOrSetAndList=" + keywordFixedOrSetAndList, module);
ComplexAlias relevancyComplexAlias = new ComplexAlias("+");
if (andKeywordFixedSet.size() > 0) {
// add up the relevancyWeight fields from all keyword member entities for a total to sort by
for (String keyword: andKeywordFixedSet) {
// make index based values and increment
String entityAlias = "PK" + index;
String prefix = "pk" + index;
index++;
dynamicViewEntity.addMemberEntity(entityAlias, "ContentKeyword");
dynamicViewEntity.addAlias(entityAlias, prefix + "Keyword", "keyword", null, null, null, null);
dynamicViewEntity.addViewLink("CNT", entityAlias, Boolean.FALSE, ModelKeyMap.makeKeyMapList("contentId"));
entityConditionList.add(EntityCondition.makeCondition(prefix + "Keyword", EntityOperator.LIKE, keyword));
//don't add an alias for this, will be part of a complex alias: dynamicViewEntity.addAlias(entityAlias, prefix + "RelevancyWeight", "relevancyWeight", null, null, null, null);
relevancyComplexAlias.addComplexAliasMember(new ComplexAliasField(entityAlias, "relevancyWeight", null, null));
}
//TODO: find out why Oracle and other dbs don't like the query resulting from this and fix: contentIdGroupBy = true;
if (!doingBothAndOr) {
dynamicViewEntity.addAlias(null, "totalRelevancy", null, null, null, null, null, relevancyComplexAlias);
}
}
if (keywordFixedOrSetAndList.size() > 0) {
for (Set<String> keywordFixedOrSet: keywordFixedOrSetAndList) {
// make index based values and increment
String entityAlias = "PK" + index;
String prefix = "pk" + index;
index++;
dynamicViewEntity.addMemberEntity(entityAlias, "ContentKeyword");
dynamicViewEntity.addAlias(entityAlias, prefix + "Keyword", "keyword", null, null, null, null);
dynamicViewEntity.addViewLink("CNT", entityAlias, Boolean.FALSE, ModelKeyMap.makeKeyMapList("contentId"));
List<EntityExpr> keywordOrList = new LinkedList<EntityExpr>();
for (String keyword: keywordFixedOrSet) {
keywordOrList.add(EntityCondition.makeCondition(prefix + "Keyword", EntityOperator.LIKE, keyword));
}
entityConditionList.add(EntityCondition.makeCondition(keywordOrList, EntityOperator.OR));
contentIdGroupBy = true;
if (doingBothAndOr) {
relevancyComplexAlias.addComplexAliasMember(new ComplexAliasField(entityAlias, "relevancyWeight", null, "sum"));
} else {
dynamicViewEntity.addAlias(entityAlias, "totalRelevancy", "relevancyWeight", null, null, null, "sum");
}
}
}
if (doingBothAndOr) {
dynamicViewEntity.addAlias(null, "totalRelevancy", null, null, null, null, null, relevancyComplexAlias);
}
}
public EntityListIterator doQuery(Delegator delegator) {
// handle the now assembled or and and keyword fixed lists
this.finishKeywordConstraints();
if (resultSortOrder != null) {
resultSortOrder.setSortOrder(this);
}
dynamicViewEntity.addAlias("CNT", "contentId", null, null, null, Boolean.valueOf(contentIdGroupBy), null);
EntityCondition whereCondition = EntityCondition.makeCondition(entityConditionList, EntityOperator.AND);
// Debug.logInfo("ContentSearch, whereCondition = " + whereCondition.toString(), module);
EntityListIterator eli = null;
try {
eli = EntityQuery.use(delegator)
.select(fieldsToSelect).from(dynamicViewEntity)
.where(whereCondition)
.cursorScrollInsensitive()
.distinct()
.maxRows(maxResults)
.queryIterator();
} catch (GenericEntityException e) {
Debug.logError(e, "Error in content search", module);
return null;
}
return eli;
}
public ArrayList<String> makeContentIdList(EntityListIterator eli) {
ArrayList<String> contentIds = new ArrayList<String>(maxResults == null ? 100 : maxResults.intValue());
if (eli == null) {
Debug.logWarning("The eli is null, returning zero results", module);
return contentIds;
}
try {
boolean hasResults = false;
Object initialResult = null;
/* this method has been replaced by the following to address issue with SAP DB and possibly other DBs
if (resultOffset != null) {
Debug.logInfo("Before relative, current index=" + eli.currentIndex(), module);
hasResults = eli.relative(resultOffset.intValue());
} else {
initialResult = eli.next();
if (initialResult != null) {
hasResults = true;
}
}
*/
initialResult = eli.next();
if (initialResult != null) {
hasResults = true;
}
if (resultOffset != null && resultOffset.intValue() > 1) {
if (Debug.infoOn()) Debug.logInfo("Before relative, current index=" + eli.currentIndex(), module);
hasResults = eli.relative(resultOffset.intValue() - 1);
initialResult = null;
}
// get the first as the current one
GenericValue searchResult = null;
if (hasResults) {
if (initialResult != null) {
searchResult = (GenericValue) initialResult;
} else {
searchResult = eli.currentGenericValue();
}
}
if (searchResult == null) {
// nothing to get...
int failTotal = 0;
if (this.resultOffset != null) {
failTotal = this.resultOffset.intValue() - 1;
}
this.totalResults = Integer.valueOf(failTotal);
return contentIds;
}
// init numRetreived to one since we have already grabbed the initial one
int numRetreived = 1;
int duplicatesFound = 0;
Set<String> contentIdSet = new HashSet<String>();
contentIds.add(searchResult.getString("contentId"));
contentIdSet.add(searchResult.getString("contentId"));
while (((searchResult = eli.next()) != null) && (maxResults == null || numRetreived < maxResults.intValue())) {
String contentId = searchResult.getString("contentId");
if (!contentIdSet.contains(contentId)) {
contentIds.add(contentId);
contentIdSet.add(contentId);
numRetreived++;
} else {
duplicatesFound++;
}
/*
StringBuilder lineMsg = new StringBuilder("Got search result line: ");
Iterator<String> fieldsToSelectIter = fieldsToSelect.iterator();
while (fieldsToSelectIter.hasNext()) {
String fieldName = fieldsToSelectIter.next();
lineMsg.append(fieldName);
lineMsg.append("=");
lineMsg.append(searchResult.get(fieldName));
if (fieldsToSelectIter.hasNext()) {
lineMsg.append(", ");
}
}
Debug.logInfo(lineMsg.toString(), module);
*/
}
if (searchResult != null) {
this.totalResults = eli.getResultsSizeAfterPartialList();
}
if (this.totalResults == null || this.totalResults.intValue() == 0) {
int total = numRetreived;
if (this.resultOffset != null) {
total += (this.resultOffset.intValue() - 1);
}
this.totalResults = Integer.valueOf(total);
}
Debug.logInfo("Got search values, numRetreived=" + numRetreived + ", totalResults=" + totalResults + ", maxResults=" + maxResults + ", resultOffset=" + resultOffset + ", duplicatesFound(in the current results)=" + duplicatesFound, module);
} catch (GenericEntityException e) {
Debug.logError(e, "Error getting results from the content search query", module);
}
return contentIds;
}
public void saveSearchResultInfo(Long numResults, Double secondsTotal) {
// uses entities: ContentSearchResult and ContentSearchConstraint
try {
// make sure this is in a transaction
boolean beganTransaction = TransactionUtil.begin();
try {
GenericValue contentSearchResult = delegator.makeValue("ContentSearchResult");
String contentSearchResultId = delegator.getNextSeqId("ContentSearchResult");
contentSearchResult.set("contentSearchResultId", contentSearchResultId);
contentSearchResult.set("visitId", this.visitId);
if (this.resultSortOrder != null) {
contentSearchResult.set("orderByName", this.resultSortOrder.getOrderName());
contentSearchResult.set("isAscending", this.resultSortOrder.isAscending() ? "Y" : "N");
}
contentSearchResult.set("numResults", numResults);
contentSearchResult.set("secondsTotal", secondsTotal);
contentSearchResult.set("searchDate", nowTimestamp);
contentSearchResult.create();
int seqId = 1;
for (GenericValue contentSearchConstraint: contentSearchConstraintList) {
contentSearchConstraint.set("contentSearchResultId", contentSearchResultId);
contentSearchConstraint.set("constraintSeqId", Integer.toString(seqId));
contentSearchConstraint.create();
seqId++;
}
TransactionUtil.commit(beganTransaction);
} catch (GenericEntityException e1) {
String errMsg = "Error saving content search result info/stats";
Debug.logError(e1, errMsg, module);
TransactionUtil.rollback(beganTransaction, errMsg, e1);
}
} catch (GenericTransactionException e) {
Debug.logError(e, "Error saving content search result info/stats", module);
}
}
}
// ======================================================================
// Search Constraint Classes
// ======================================================================
@SuppressWarnings("serial")
public static abstract class ContentSearchConstraint implements java.io.Serializable {
public ContentSearchConstraint() { }
public abstract void addConstraint(ContentSearchContext contentSearchContext);
/** pretty print for log messages and even UI stuff */
public abstract String prettyPrintConstraint(Delegator delegator, boolean detailed, Locale locale);
}
@SuppressWarnings("serial")
public static class ContentAssocConstraint extends ContentSearchConstraint {
public static final String constraintName = "ContentAssoc";
protected String contentId;
protected String contentAssocTypeId;
protected boolean includeSubContents;
public ContentAssocConstraint(String contentId, String contentAssocTypeId, boolean includeSubContents) {
this.contentId = contentId;
this.contentAssocTypeId = contentAssocTypeId;
this.includeSubContents = includeSubContents;
}
@Override
public void addConstraint(ContentSearchContext contentSearchContext) {
Set<String> contentIdSet = new HashSet<String>();
if (includeSubContents) {
// find all sub-categories recursively, make a Set of contentId
ContentSearch.getAllSubContentIds(contentId, contentIdSet, contentSearchContext.getDelegator(), contentSearchContext.nowTimestamp);
} else {
contentIdSet.add(contentId);
}
// allow assoc from or to the current WE and the contentId on this constraint
// make index based values and increment
String entityAlias;
String prefix;
// do contentId = contentIdFrom, contentIdTo IN contentIdSet
entityAlias = "CNT" + contentSearchContext.index;
prefix = "cnt" + contentSearchContext.index;
contentSearchContext.index++;
contentSearchContext.dynamicViewEntity.addMemberEntity(entityAlias, "ContentAssoc");
contentSearchContext.dynamicViewEntity.addAlias(entityAlias, prefix + "ContentIdFrom", "contentIdFrom", null, null, null, null);
contentSearchContext.dynamicViewEntity.addAlias(entityAlias, prefix + "ContentIdTo", "contentIdTo", null, null, null, null);
contentSearchContext.dynamicViewEntity.addAlias(entityAlias, prefix + "ContentAssocTypeId", "contentAssocTypeId", null, null, null, null);
contentSearchContext.dynamicViewEntity.addAlias(entityAlias, prefix + "FromDate", "fromDate", null, null, null, null);
contentSearchContext.dynamicViewEntity.addAlias(entityAlias, prefix + "ThruDate", "thruDate", null, null, null, null);
contentSearchContext.dynamicViewEntity.addViewLink("CNT", entityAlias, Boolean.TRUE, ModelKeyMap.makeKeyMapList("contentId","contentIdFrom"));
List<EntityExpr> assocConditionFromTo = new LinkedList<EntityExpr>();
assocConditionFromTo.add(EntityCondition.makeCondition(prefix + "ContentIdTo", EntityOperator.IN, contentIdSet));
if (UtilValidate.isNotEmpty(contentAssocTypeId)) {
assocConditionFromTo.add(EntityCondition.makeCondition(prefix + "ContentAssocTypeId", EntityOperator.EQUALS, contentAssocTypeId));
}
assocConditionFromTo.add(EntityCondition.makeCondition(EntityCondition.makeCondition(prefix + "ThruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition(prefix + "ThruDate", EntityOperator.GREATER_THAN, contentSearchContext.nowTimestamp)));
assocConditionFromTo.add(EntityCondition.makeCondition(prefix + "FromDate", EntityOperator.LESS_THAN, contentSearchContext.nowTimestamp));
// do contentId = contentIdTo, contentIdFrom IN contentIdSet
entityAlias = "CNT" + contentSearchContext.index;
prefix = "cnt" + contentSearchContext.index;
contentSearchContext.index++;
contentSearchContext.dynamicViewEntity.addMemberEntity(entityAlias, "ContentAssoc");
contentSearchContext.dynamicViewEntity.addAlias(entityAlias, prefix + "ContentIdFrom", "contentIdFrom", null, null, null, null);
contentSearchContext.dynamicViewEntity.addAlias(entityAlias, prefix + "ContentIdTo", "contentIdTo", null, null, null, null);
contentSearchContext.dynamicViewEntity.addAlias(entityAlias, prefix + "ContentAssocTypeId", "contentAssocTypeId", null, null, null, null);
contentSearchContext.dynamicViewEntity.addAlias(entityAlias, prefix + "FromDate", "fromDate", null, null, null, null);
contentSearchContext.dynamicViewEntity.addAlias(entityAlias, prefix + "ThruDate", "thruDate", null, null, null, null);
contentSearchContext.dynamicViewEntity.addViewLink("CNT", entityAlias, Boolean.TRUE, ModelKeyMap.makeKeyMapList("contentId","contentIdTo"));
List<EntityExpr> assocConditionToFrom = new LinkedList<EntityExpr>();
assocConditionToFrom.add(EntityCondition.makeCondition(prefix + "ContentIdFrom", EntityOperator.IN, contentIdSet));
if (UtilValidate.isNotEmpty(contentAssocTypeId)) {
assocConditionToFrom.add(EntityCondition.makeCondition(prefix + "ContentAssocTypeId", EntityOperator.EQUALS, contentAssocTypeId));
}
assocConditionToFrom.add(EntityCondition.makeCondition(EntityCondition.makeCondition(prefix + "ThruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition(prefix + "ThruDate", EntityOperator.GREATER_THAN, contentSearchContext.nowTimestamp)));
assocConditionToFrom.add(EntityCondition.makeCondition(prefix + "FromDate", EntityOperator.LESS_THAN, contentSearchContext.nowTimestamp));
// now create and add the combined constraint
contentSearchContext.entityConditionList.add(EntityCondition.makeCondition(EntityCondition.makeCondition(assocConditionFromTo, EntityOperator.AND), EntityOperator.OR, EntityCondition.makeCondition(assocConditionToFrom, EntityOperator.AND)));
// add in contentSearchConstraint, don't worry about the contentSearchResultId or constraintSeqId, those will be fill in later
contentSearchContext.contentSearchConstraintList.add(contentSearchContext.getDelegator().makeValue("ContentSearchConstraint", UtilMisc.toMap("constraintName", constraintName, "infoString", this.contentId + "," + this.contentAssocTypeId, "includeSubContents", this.includeSubContents ? "Y" : "N")));
}
/** pretty print for log messages and even UI stuff */
@Override
public String prettyPrintConstraint(Delegator delegator, boolean detailed, Locale locale) {
GenericValue content = null;
GenericValue contentAssocType = null;
try {
content = EntityQuery.use(delegator).from("Content").where("contentId", this.contentId).cache().queryOne();
contentAssocType = EntityQuery.use(delegator).from("ContentAssocType").where("contentAssocTypeId", this.contentAssocTypeId).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Error looking up ContentAssocConstraint pretty print info: " + e.toString(), module);
}
StringBuilder ppBuf = new StringBuilder();
ppBuf.append(UtilProperties.getMessage(resource, "ContentAssoc", locale) + ": ");
if (content != null) {
ppBuf.append(content.getString("contentName"));
}
if (content == null || detailed) {
ppBuf.append(" [");
ppBuf.append(contentId);
ppBuf.append("]");
}
if (UtilValidate.isNotEmpty(this.contentAssocTypeId)) {
if (contentAssocType != null) {
ppBuf.append(contentAssocType.getString("description"));
}
if (contentAssocType == null || detailed) {
ppBuf.append(" [");
ppBuf.append(contentAssocTypeId);
ppBuf.append("]");
}
}
if (this.includeSubContents) {
ppBuf.append(" (").append(UtilProperties.getMessage(resource, "ContentIncludeAllSubContents", locale)).append(")");
}
return ppBuf.toString();
}
@Override
public boolean equals(Object obj) {
ContentSearchConstraint psc = (ContentSearchConstraint) obj;
if (psc instanceof ContentAssocConstraint) {
ContentAssocConstraint that = (ContentAssocConstraint) psc;
if (this.includeSubContents != that.includeSubContents) {
return false;
}
if (this.contentId == null) {
if (that.contentId != null) {
return false;
}
} else {
if (!this.contentId.equals(that.contentId)) {
return false;
}
}
if (this.contentAssocTypeId == null) {
if (that.contentAssocTypeId != null) {
return false;
}
} else {
if (!this.contentAssocTypeId.equals(that.contentAssocTypeId)) {
return false;
}
}
return true;
} else {
return false;
}
}
}
@SuppressWarnings("serial")
public static class KeywordConstraint extends ContentSearchConstraint {
public static final String constraintName = "Keyword";
protected String keywordsString;
protected boolean anyPrefix;
protected boolean anySuffix;
protected boolean isAnd;
protected boolean removeStems;
public KeywordConstraint(String keywordsString, boolean anyPrefix, boolean anySuffix, Boolean removeStems, boolean isAnd) {
this.keywordsString = keywordsString;
this.anyPrefix = anyPrefix;
this.anySuffix = anySuffix;
this.isAnd = isAnd;
if (removeStems != null) {
this.removeStems = removeStems.booleanValue();
} else {
this.removeStems = UtilProperties.propertyValueEquals("keywordsearch", "remove.stems", "true");
}
}
public Set<String> makeFullKeywordSet(Delegator delegator) {
Set<String> keywordSet = KeywordSearchUtil.makeKeywordSet(this.keywordsString, null, true);
Set<String> fullKeywordSet = new TreeSet<String>();
// expand the keyword list according to the thesaurus and create a new set of keywords
for (String keyword: keywordSet) {
Set<String> expandedSet = new TreeSet<String>();
boolean replaceEntered = KeywordSearchUtil.expandKeywordForSearch(keyword, expandedSet, delegator);
fullKeywordSet.addAll(expandedSet);
if (!replaceEntered) {
fullKeywordSet.add(keyword);
}
}
return fullKeywordSet;
}
@Override
public void addConstraint(ContentSearchContext contentSearchContext) {
// just make the fixed keyword lists and put them in the context
if (isAnd) {
// when isAnd is true we need to make a list of keyword sets where each set corresponds to one
//incoming/entered keyword and contains all of the expanded keywords plus the entered keyword if none of
//the expanded keywords are flagged as replacements; now the tricky part: each set should be or'ed together,
//but then the sets should be and'ed to produce the overall expression; create the SQL for this
//needs some work as the current method only support a list of and'ed words and a list of or'ed words, not
//a list of or'ed sets to be and'ed together
Set<String> keywordSet = KeywordSearchUtil.makeKeywordSet(this.keywordsString, null, true);
// expand the keyword list according to the thesaurus and create a new set of keywords
for (String keyword: keywordSet) {
Set<String> expandedSet = new TreeSet<String>();
boolean replaceEntered = KeywordSearchUtil.expandKeywordForSearch(keyword, expandedSet, contentSearchContext.getDelegator());
if (!replaceEntered) {
expandedSet.add(keyword);
}
Set<String> fixedSet = KeywordSearchUtil.fixKeywordsForSearch(expandedSet, anyPrefix, anySuffix, removeStems, isAnd);
Set<String> fixedKeywordSet = new HashSet<String>();
fixedKeywordSet.addAll(fixedSet);
contentSearchContext.keywordFixedOrSetAndList.add(fixedKeywordSet);
}
} else {
// when isAnd is false, just add all of the new entries to the big list
Set<String> keywordFirstPass = makeFullKeywordSet(contentSearchContext.getDelegator()); // includes keyword expansion, etc
Set<String> keywordSet = KeywordSearchUtil.fixKeywordsForSearch(keywordFirstPass, anyPrefix, anySuffix, removeStems, isAnd);
contentSearchContext.orKeywordFixedSet.addAll(keywordSet);
}
// add in contentSearchConstraint, don't worry about the contentSearchResultId or constraintSeqId, those will be fill in later
Map<String, String> valueMap = UtilMisc.toMap("constraintName", constraintName, "infoString", this.keywordsString);
valueMap.put("anyPrefix", this.anyPrefix ? "Y" : "N");
valueMap.put("anySuffix", this.anySuffix ? "Y" : "N");
valueMap.put("isAnd", this.isAnd ? "Y" : "N");
valueMap.put("removeStems", this.removeStems ? "Y" : "N");
contentSearchContext.contentSearchConstraintList.add(contentSearchContext.getDelegator().makeValue("ContentSearchConstraint", valueMap));
}
/** pretty print for log messages and even UI stuff */
@Override
public String prettyPrintConstraint(Delegator delegator, boolean detailed, Locale locale) {
StringBuilder ppBuf = new StringBuilder();
ppBuf.append(UtilProperties.getMessage(resource, "ContentKeywords", locale)).append(": \"");
ppBuf.append(this.keywordsString).append("\", ").append(UtilProperties.getMessage(resource, "ContentKeywordWhere", locale)).append(" ");
ppBuf.append(isAnd ? UtilProperties.getMessage(resource, "ContentKeywordAllWordsMatch", locale) : UtilProperties.getMessage(resource, "ContentKeywordAnyWordMatches", locale));
return ppBuf.toString();
}
@Override
public boolean equals(Object obj) {
ContentSearchConstraint psc = (ContentSearchConstraint) obj;
if (psc instanceof KeywordConstraint) {
KeywordConstraint that = (KeywordConstraint) psc;
if (this.anyPrefix != that.anyPrefix) {
return false;
}
if (this.anySuffix != that.anySuffix) {
return false;
}
if (this.isAnd != that.isAnd) {
return false;
}
if (this.removeStems != that.removeStems) {
return false;
}
if (this.keywordsString == null) {
if (that.keywordsString != null) {
return false;
}
} else {
if (!this.keywordsString.equals(that.keywordsString)) {
return false;
}
}
return true;
} else {
return false;
}
}
}
@SuppressWarnings("serial")
public static class LastUpdatedRangeConstraint extends ContentSearchConstraint {
public static final String constraintName = "LastUpdatedRange";
protected Timestamp fromDate;
protected Timestamp thruDate;
public LastUpdatedRangeConstraint(Timestamp fromDate, Timestamp thruDate) {
this.fromDate = fromDate;
this.thruDate = thruDate;
}
@Override
public void addConstraint(ContentSearchContext contentSearchContext) {
contentSearchContext.dynamicViewEntity.addAlias("CNT", "lastModifiedDate", "lastModifiedDate", null, null, null, null);
EntityConditionList<EntityExpr> dateConditions = null;
EntityExpr dateCondition=null;
if (fromDate !=null && thruDate!=null) {
dateConditions= EntityCondition.makeCondition(UtilMisc.toList(
EntityCondition.makeCondition("lastModifiedDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate),
EntityCondition.makeCondition("lastModifiedDate", EntityOperator.LESS_THAN_EQUAL_TO, thruDate)), EntityOperator.AND);
} if (fromDate !=null) {
dateCondition=EntityCondition.makeCondition("lastModifiedDate", EntityOperator.GREATER_THAN_EQUAL_TO, fromDate);
} else if (thruDate != null) {
dateCondition = EntityCondition.makeCondition("lastModifiedDate", EntityOperator.LESS_THAN_EQUAL_TO, thruDate);
}
EntityConditionList<? extends EntityCondition> conditions = null;
if (fromDate !=null && thruDate!=null) {
conditions=EntityCondition.makeCondition(UtilMisc.toList(
dateConditions,
EntityCondition.makeCondition("lastModifiedDate", EntityOperator.EQUALS, null)),
EntityOperator.OR);
} else {
conditions=EntityCondition.makeCondition(UtilMisc.toList(
dateCondition,
EntityCondition.makeCondition("lastModifiedDate", EntityOperator.EQUALS, null)),
EntityOperator.OR);
}
contentSearchContext.entityConditionList.add(conditions);
// add in contentSearchConstraint, don't worry about the contentSearchResultId or constraintSeqId, those will be fill in later
contentSearchContext.contentSearchConstraintList.add(contentSearchContext.getDelegator().makeValue("ContentSearchConstraint", UtilMisc.toMap("constraintName", constraintName, "infoString","fromDate : " + fromDate + " thruDate : " + thruDate)));
}
/** pretty print for log messages and even UI stuff */
@Override
public String prettyPrintConstraint(Delegator delegator, boolean detailed, Locale locale) {
StringBuilder ppBuf = new StringBuilder();
ppBuf.append(UtilProperties.getMessage(resource, "ContentLastModified", locale)).append(": \"");
ppBuf.append(fromDate).append("-").append(thruDate).append("\", ").append(UtilProperties.getMessage(resource, "ContentLastModified", locale)).append(" ");
return ppBuf.toString();
}
@Override
public boolean equals(Object obj) {
ContentSearchConstraint psc = (ContentSearchConstraint) obj;
if (psc instanceof LastUpdatedRangeConstraint) {
LastUpdatedRangeConstraint that = (LastUpdatedRangeConstraint) psc;
if (this.fromDate == null) {
if (that.fromDate != null) {
return false;
}
} else {
if (!this.fromDate.equals(that.fromDate)) {
return false;
}
}
if (this.thruDate == null) {
if (that.thruDate != null) {
return false;
}
} else {
if (!this.thruDate.equals(that.thruDate)) {
return false;
}
}
return true;
} else {
return false;
}
}
}
// ======================================================================
// Result Sort Classes
// ======================================================================
@SuppressWarnings("serial")
public static abstract class ResultSortOrder implements java.io.Serializable {
public ResultSortOrder() {
}
public abstract void setSortOrder(ContentSearchContext contentSearchContext);
public abstract String getOrderName();
public abstract String prettyPrintSortOrder(boolean detailed, Locale locale);
public abstract boolean isAscending();
}
@SuppressWarnings("serial")
public static class SortKeywordRelevancy extends ResultSortOrder {
public SortKeywordRelevancy() {
}
@Override
public void setSortOrder(ContentSearchContext contentSearchContext) {
if (contentSearchContext.includedKeywordSearch) {
// we have to check this in order to be sure that there is a totalRelevancy to sort by...
contentSearchContext.orderByList.add("-totalRelevancy");
contentSearchContext.fieldsToSelect.add("totalRelevancy");
}
}
@Override
public String getOrderName() {
return "KeywordRelevancy";
}
@Override
public String prettyPrintSortOrder(boolean detailed, Locale locale) {
return UtilProperties.getMessage(resource, "ContentKeywordRelevancy", locale);
}
@Override
public boolean isAscending() {
return false;
}
}
@SuppressWarnings("serial")
public static class SortContentField extends ResultSortOrder {
protected String fieldName;
protected boolean ascending;
/** Some good field names to try might include:
* [contentName]
* [totalQuantityOrdered] for most popular or most purchased
* [lastModifiedDate]
*
* You can also include any other field on the Content entity.
*/
public SortContentField(String fieldName, boolean ascending) {
this.fieldName = fieldName;
this.ascending = ascending;
}
@Override
public void setSortOrder(ContentSearchContext contentSearchContext) {
if (contentSearchContext.getDelegator().getModelEntity("Content").isField(fieldName)) {
contentSearchContext.dynamicViewEntity.addAlias("CNT", fieldName);
}
if (ascending) {
contentSearchContext.orderByList.add("+" + fieldName);
} else {
contentSearchContext.orderByList.add("-" + fieldName);
}
contentSearchContext.fieldsToSelect.add(fieldName);
}
@Override
public String getOrderName() {
return "ContentField:" + this.fieldName;
}
@Override
public String prettyPrintSortOrder(boolean detailed, Locale locale) {
if ("contentName".equals(this.fieldName)) {
return UtilProperties.getMessage(resource, "ContentName", locale);
} else if ("totalQuantityOrdered".equals(this.fieldName)) {
return UtilProperties.getMessage(resource, "ContentPopularityByOrders", locale);
} else if ("totalTimesViewed".equals(this.fieldName)) {
return UtilProperties.getMessage(resource, "ContentPopularityByViews", locale);
} else if ("averageCustomerRating".equals(this.fieldName)) {
return UtilProperties.getMessage(resource, "ContentCustomerRating", locale);
}
return this.fieldName;
}
@Override
public boolean isAscending() {
return this.ascending;
}
}
}
@@ -0,0 +1,116 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.webapp.stats.VisitHandler;
import org.ofbiz.content.content.ContentSearch.ResultSortOrder;
import org.ofbiz.content.content.ContentSearch.ContentSearchConstraint;
import org.ofbiz.content.content.ContentSearch.ContentSearchContext;
import org.ofbiz.content.content.ContentSearchSession.ContentSearchOptions;
public class ContentSearchEvents {
public static final String module = ContentSearchEvents.class.getName();
public static Map<String, Object> getContentSearchResult(HttpServletRequest request, Delegator delegator) {
// ========== Create View Indexes
int viewIndex = 0;
int viewSize = 20;
int highIndex = 0;
int lowIndex = 0;
int listSize = 0;
HttpSession session = request.getSession();
ContentSearchOptions contentSearchOptions = ContentSearchSession.getContentSearchOptions(session);
Integer viewIndexInteger = contentSearchOptions.getViewIndex();
if (viewIndexInteger != null) viewIndex = viewIndexInteger.intValue();
Integer viewSizeInteger = contentSearchOptions.getViewSize();
if (viewSizeInteger != null) viewSize = viewSizeInteger.intValue();
lowIndex = viewIndex * viewSize;
highIndex = (viewIndex + 1) * viewSize;
// setup resultOffset and maxResults, noting that resultOffset is 1 based, not zero based as these numbers
Integer resultOffset = Integer.valueOf(lowIndex + 1);
Integer maxResults = Integer.valueOf(viewSize);
// ========== Do the actual search
ArrayList<String> contentIds = null;
String visitId = VisitHandler.getVisitId(session);
List<ContentSearchConstraint> contentSearchConstraintList = ContentSearchOptions.getConstraintList(session);
// if no constraints, don't do a search...
if (UtilValidate.isNotEmpty(contentSearchConstraintList)) {
// if the search options have changed since the last search, put at the beginning of the options history list
ContentSearchSession.checkSaveSearchOptionsHistory(session);
ResultSortOrder resultSortOrder = ContentSearchOptions.getResultSortOrder(request);
ContentSearchContext contentSearchContext = new ContentSearchContext(delegator, visitId);
contentSearchContext.addContentSearchConstraints(contentSearchConstraintList);
contentSearchContext.setResultSortOrder(resultSortOrder);
contentSearchContext.setResultOffset(resultOffset);
contentSearchContext.setMaxResults(maxResults);
contentIds = contentSearchContext.doSearch();
Integer totalResults = contentSearchContext.getTotalResults();
if (totalResults != null) {
listSize = totalResults.intValue();
}
}
if (listSize < highIndex) {
highIndex = listSize;
}
// ========== Setup other display info
List<String> searchConstraintStrings = ContentSearchSession.searchGetConstraintStrings(false, session, delegator);
String searchSortOrderString = ContentSearchSession.searchGetSortOrderString(false, request);
// ========== populate the result Map
Map<String, Object> result = new HashMap<String, Object>();
result.put("contentIds", contentIds);
result.put("viewIndex", Integer.valueOf(viewIndex));
result.put("viewSize", Integer.valueOf(viewSize));
result.put("listSize", Integer.valueOf(listSize));
result.put("lowIndex", Integer.valueOf(lowIndex));
result.put("highIndex", Integer.valueOf(highIndex));
result.put("searchConstraintStrings", searchConstraintStrings);
result.put("searchSortOrderString", searchSortOrderString);
return result;
}
}
@@ -0,0 +1,309 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.content.content.ContentSearch.ResultSortOrder;
import org.ofbiz.content.content.ContentSearch.SortKeywordRelevancy;
import org.ofbiz.content.content.ContentSearch.ContentSearchConstraint;
public class ContentSearchSession {
public static final String module = ContentSearchSession.class.getName();
@SuppressWarnings("serial")
public static class ContentSearchOptions implements java.io.Serializable {
protected List<ContentSearchConstraint> constraintList = null;
protected ResultSortOrder resultSortOrder = null;
protected Integer viewIndex = null;
protected Integer viewSize = null;
protected boolean changed = false;
public ContentSearchOptions() { }
/** Basic copy constructor */
public ContentSearchOptions(ContentSearchOptions contentSearchOptions) {
this.constraintList = UtilMisc.makeListWritable(contentSearchOptions.constraintList);
this.resultSortOrder = contentSearchOptions.resultSortOrder;
this.viewIndex = contentSearchOptions.viewIndex;
this.viewSize = contentSearchOptions.viewSize;
this.changed = contentSearchOptions.changed;
}
public List<ContentSearchConstraint> getConstraintList() {
return this.constraintList;
}
public static List<ContentSearchConstraint> getConstraintList(HttpSession session) {
return getContentSearchOptions(session).constraintList;
}
public static void addConstraint(ContentSearchConstraint contentSearchConstraint, HttpSession session) {
ContentSearchOptions contentSearchOptions = getContentSearchOptions(session);
if (contentSearchOptions.constraintList == null) {
contentSearchOptions.constraintList = new LinkedList<ContentSearch.ContentSearchConstraint>();
}
if (!contentSearchOptions.constraintList.contains(contentSearchConstraint)) {
contentSearchOptions.constraintList.add(contentSearchConstraint);
contentSearchOptions.changed = true;
}
}
public ResultSortOrder getResultSortOrder() {
if (this.resultSortOrder == null) {
this.resultSortOrder = new SortKeywordRelevancy();
this.changed = true;
}
return this.resultSortOrder;
}
public static ResultSortOrder getResultSortOrder(HttpServletRequest request) {
ContentSearchOptions contentSearchOptions = getContentSearchOptions(request.getSession());
return contentSearchOptions.getResultSortOrder();
}
public static void setResultSortOrder(ResultSortOrder resultSortOrder, HttpSession session) {
ContentSearchOptions contentSearchOptions = getContentSearchOptions(session);
contentSearchOptions.resultSortOrder = resultSortOrder;
contentSearchOptions.changed = true;
}
public static void clearSearchOptions(HttpSession session) {
ContentSearchOptions contentSearchOptions = getContentSearchOptions(session);
contentSearchOptions.constraintList = null;
contentSearchOptions.resultSortOrder = null;
}
public void clearViewInfo() {
this.viewIndex = null;
this.viewSize = null;
}
/**
* @return Returns the viewIndex.
*/
public Integer getViewIndex() {
return viewIndex;
}
/**
* @param viewIndex The viewIndex to set.
*/
public void setViewIndex(Integer viewIndex) {
this.viewIndex = viewIndex;
}
/**
* @return Returns the viewSize.
*/
public Integer getViewSize() {
return viewSize;
}
/**
* @param viewSize The viewSize to set.
*/
public void setViewSize(Integer viewSize) {
this.viewSize = viewSize;
}
public List<String> searchGetConstraintStrings(boolean detailed, Delegator delegator, Locale locale) {
List<ContentSearchConstraint> contentSearchConstraintList = this.getConstraintList();
List<String> constraintStrings = new LinkedList<String>();
if (contentSearchConstraintList == null) {
return constraintStrings;
}
for (ContentSearchConstraint contentSearchConstraint: contentSearchConstraintList) {
if (contentSearchConstraint == null) continue;
String constraintString = contentSearchConstraint.prettyPrintConstraint(delegator, detailed, locale);
if (UtilValidate.isNotEmpty(constraintString)) {
constraintStrings.add(constraintString);
} else {
constraintStrings.add("Description not available");
}
}
return constraintStrings;
}
}
public static ContentSearchOptions getContentSearchOptions(HttpSession session) {
ContentSearchOptions contentSearchOptions = (ContentSearchOptions) session.getAttribute("_CONTENT_SEARCH_OPTIONS_CURRENT_");
if (contentSearchOptions == null) {
contentSearchOptions = new ContentSearchOptions();
session.setAttribute("_CONTENT_SEARCH_OPTIONS_CURRENT_", contentSearchOptions);
}
return contentSearchOptions;
}
public static void processSearchParameters(Map<String, Object> parameters, HttpServletRequest request) {
Boolean alreadyRun = (Boolean) request.getAttribute("processSearchParametersAlreadyRun");
if (Boolean.TRUE.equals(alreadyRun)) {
return;
} else {
request.setAttribute("processSearchParametersAlreadyRun", Boolean.TRUE);
}
HttpSession session = request.getSession();
boolean constraintsChanged = false;
// clear search? by default yes, but if the clearSearch parameter is N then don't
String clearSearchString = (String) parameters.get("clearSearch");
if (!"N".equals(clearSearchString)) {
searchClear(session);
constraintsChanged = true;
} else {
String removeConstraint = (String) parameters.get("removeConstraint");
if (UtilValidate.isNotEmpty(removeConstraint)) {
try {
searchRemoveConstraint(Integer.parseInt(removeConstraint), session);
constraintsChanged = true;
} catch (Exception e) {
Debug.logError(e, "Error removing constraint [" + removeConstraint + "]", module);
}
}
}
// add a Content Assoc Type to the search
if (UtilValidate.isNotEmpty(parameters.get("SEARCH_CONTENT_ID"))) {
String contentId=(String) parameters.get("SEARCH_CONTENT_ID");
String contentAssocTypeId=(String) parameters.get("contentAssocTypeId");
boolean includeAllSubContents =!"N".equalsIgnoreCase((String) parameters.get("SEARCH_SUB_CONTENTS"));
searchAddConstraint(new ContentSearch.ContentAssocConstraint(contentId,contentAssocTypeId,includeAllSubContents), session);
constraintsChanged = true;
}
// add a Content fromDate thruDate to the search
if (UtilValidate.isNotEmpty(parameters.get("fromDate")) || UtilValidate.isNotEmpty(parameters.get("thruDate"))) {
Timestamp fromDate =null;
if (UtilValidate.isNotEmpty(parameters.get("fromDate"))) {
fromDate=Timestamp.valueOf((String) parameters.get("fromDate"));
}
Timestamp thruDate = null;
if (UtilValidate.isNotEmpty(parameters.get("thruDate"))) {
thruDate = Timestamp.valueOf((String) parameters.get("thruDate"));
}
searchAddConstraint(new ContentSearch.LastUpdatedRangeConstraint(fromDate,thruDate), session);
constraintsChanged = true;
}
// if keywords were specified, add a constraint for them
if (UtilValidate.isNotEmpty(parameters.get("SEARCH_STRING"))) {
String keywordString = (String) parameters.get("SEARCH_STRING");
String searchOperator = (String) parameters.get("SEARCH_OPERATOR");
// defaults to true/Y, ie anything but N is true/Y
boolean anyPrefixSuffix = !"N".equals(parameters.get("SEARCH_ANYPRESUF"));
searchAddConstraint(new ContentSearch.KeywordConstraint(keywordString, anyPrefixSuffix, anyPrefixSuffix, null, "AND".equals(searchOperator)), session);
constraintsChanged = true;
}
// set the sort order
String sortOrder = (String) parameters.get("sortOrder");
String sortAscending = (String) parameters.get("sortAscending");
boolean ascending = !"N".equals(sortAscending);
if (sortOrder != null) {
if (sortOrder.equals("SortKeywordRelevancy")) {
searchSetSortOrder(new ContentSearch.SortKeywordRelevancy(), session);
} else if (sortOrder.startsWith("SortContentField:")) {
String fieldName = sortOrder.substring("SortContentField:".length());
searchSetSortOrder(new ContentSearch.SortContentField(fieldName, ascending), session);
}
}
ContentSearchOptions contentSearchOptions = getContentSearchOptions(session);
if (constraintsChanged) {
// query changed, clear out the VIEW_INDEX & VIEW_SIZE
contentSearchOptions.clearViewInfo();
}
String viewIndexStr = (String) parameters.get("VIEW_INDEX");
if (UtilValidate.isNotEmpty(viewIndexStr)) {
try {
contentSearchOptions.setViewIndex(Integer.valueOf(viewIndexStr));
} catch (Exception e) {
Debug.logError(e, "Error formatting VIEW_INDEX, setting to 0", module);
// we could just do nothing here, but we know something was specified so we don't want to use the previous value from the session
contentSearchOptions.setViewIndex(Integer.valueOf(0));
}
}
String viewSizeStr = (String) parameters.get("VIEW_SIZE");
if (UtilValidate.isNotEmpty(viewSizeStr)) {
try {
contentSearchOptions.setViewSize(Integer.valueOf(viewSizeStr));
} catch (Exception e) {
Debug.logError(e, "Error formatting VIEW_SIZE, setting to 20", module);
contentSearchOptions.setViewSize(Integer.valueOf(20));
}
}
}
public static void searchAddConstraint(ContentSearchConstraint contentSearchConstraint, HttpSession session) {
ContentSearchOptions.addConstraint(contentSearchConstraint, session);
}
public static void searchSetSortOrder(ResultSortOrder resultSortOrder, HttpSession session) {
ContentSearchOptions.setResultSortOrder(resultSortOrder, session);
}
public static List<ContentSearchOptions> getSearchOptionsHistoryList(HttpSession session) {
List<ContentSearchOptions> optionsHistoryList = UtilGenerics.checkList(session.getAttribute("_CONTENT_SEARCH_OPTIONS_HISTORY_"));
if (optionsHistoryList == null) {
optionsHistoryList = new LinkedList<ContentSearchSession.ContentSearchOptions>();
session.setAttribute("_CONTENT_SEARCH_OPTIONS_HISTORY_", optionsHistoryList);
}
return optionsHistoryList;
}
public static List<String> searchGetConstraintStrings(boolean detailed, HttpSession session, Delegator delegator) {
Locale locale = UtilHttp.getLocale(session);
ContentSearchOptions contentSearchOptions = getContentSearchOptions(session);
return contentSearchOptions.searchGetConstraintStrings(detailed, delegator, locale);
}
public static String searchGetSortOrderString(boolean detailed, HttpServletRequest request) {
Locale locale = UtilHttp.getLocale(request);
ResultSortOrder resultSortOrder = ContentSearchOptions.getResultSortOrder(request);
if (resultSortOrder == null) return "";
return resultSortOrder.prettyPrintSortOrder(detailed, locale);
}
public static void checkSaveSearchOptionsHistory(HttpSession session) {
ContentSearchOptions contentSearchOptions = ContentSearchSession.getContentSearchOptions(session);
// if the options have changed since the last search, add it to the beginning of the search options history
if (contentSearchOptions.changed) {
List<ContentSearchOptions> optionsHistoryList = ContentSearchSession.getSearchOptionsHistoryList(session);
optionsHistoryList.add(0, new ContentSearchOptions(contentSearchOptions));
contentSearchOptions.changed = false;
}
}
public static void searchRemoveConstraint(int index, HttpSession session) {
List<ContentSearchConstraint> contentSearchConstraintList = ContentSearchOptions.getConstraintList(session);
if (contentSearchConstraintList == null) {
return;
} else if (index >= contentSearchConstraintList.size()) {
return;
} else {
contentSearchConstraintList.remove(index);
}
}
public static void searchClear(HttpSession session) {
ContentSearchOptions.clearSearchOptions(session);
}
}
@@ -0,0 +1,293 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityConditionList;
import org.ofbiz.entity.condition.EntityExpr;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.minilang.MiniLangException;
import org.ofbiz.minilang.SimpleMapProcessor;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;
/**
* ContentServicesComplex Class
*/
public class ContentServicesComplex {
public static final String module = ContentServicesComplex.class.getName();
/*
* A service that returns a list of ContentAssocDataResourceViewFrom/To views that are
* associated with the passed in contentId. Other conditions are also applied, including:
* a list of contentAssocTypeIds or contentTypeIds that the result set views must match.
* A direction (From or To - case insensitive).
* From and thru dates or date strings.
* A mapKey value.
*/
public static Map<String, Object> getAssocAndContentAndDataResource(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
List<String> assocTypes = UtilGenerics.checkList(context.get("assocTypes"));
List<String> contentTypes = UtilGenerics.checkList(context.get("contentTypes"));
Timestamp fromDate = (Timestamp)context.get("fromDate");
Timestamp thruDate = (Timestamp)context.get("thruDate");
String fromDateStr = (String)context.get("fromDateStr");
String thruDateStr = (String)context.get("thruDateStr");
String contentId = (String)context.get("contentId");
String direction = (String)context.get("direction");
String mapKey = (String)context.get("mapKey");
// Boolean nullThruDatesOnly = (Boolean)context.get("nullThruDatesOnly");
Map<String, Object> results = getAssocAndContentAndDataResourceMethod(delegator, contentId, mapKey, direction, fromDate, thruDate, fromDateStr, thruDateStr, assocTypes, contentTypes);
return results;
}
public static Map<String, Object> getAssocAndContentAndDataResourceMethod(Delegator delegator, String contentId, String mapKey, String direction, Timestamp fromDate, Timestamp thruDate, String fromDateStr, String thruDateStr, List<String> assocTypes, List<String> contentTypes) {
List<EntityCondition> exprList = new LinkedList<EntityCondition>();
EntityExpr joinExpr = null;
String viewName = null;
if (mapKey != null) {
EntityExpr mapKeyExpr = EntityCondition.makeCondition("caMapKey", EntityOperator.EQUALS, mapKey);
exprList.add(mapKeyExpr);
}
if (direction != null && direction.equalsIgnoreCase("From")) {
joinExpr = EntityCondition.makeCondition("caContentIdTo", EntityOperator.EQUALS, contentId);
viewName = "ContentAssocDataResourceViewFrom";
} else {
joinExpr = EntityCondition.makeCondition("caContentId", EntityOperator.EQUALS, contentId);
viewName = "ContentAssocDataResourceViewTo";
}
exprList.add(joinExpr);
if (UtilValidate.isNotEmpty(assocTypes)) {
exprList.add(EntityCondition.makeCondition("caContentAssocTypeId", EntityOperator.IN, assocTypes));
}
if (UtilValidate.isNotEmpty(contentTypes)) {
exprList.add(EntityCondition.makeCondition("contentTypeId", EntityOperator.IN, contentTypes));
}
if (fromDate == null && fromDateStr != null) {
fromDate = UtilDateTime.toTimestamp(fromDateStr);
}
if (thruDate == null && thruDateStr != null) {
thruDate = UtilDateTime.toTimestamp(thruDateStr);
}
if (fromDate != null) {
EntityExpr fromExpr = EntityCondition.makeCondition("caFromDate", EntityOperator.LESS_THAN, fromDate);
exprList.add(fromExpr);
}
if (thruDate != null) {
List<EntityExpr> thruList = new LinkedList<EntityExpr>();
//thruDate = UtilDateTime.getDayStart(thruDate, daysLater);
EntityExpr thruExpr = EntityCondition.makeCondition("caThruDate", EntityOperator.LESS_THAN, thruDate);
thruList.add(thruExpr);
EntityExpr thruExpr2 = EntityCondition.makeCondition("caThruDate", EntityOperator.EQUALS, null);
thruList.add(thruExpr2);
EntityConditionList<EntityExpr> thruExprList = EntityCondition.makeCondition(thruList, EntityOperator.OR);
exprList.add(thruExprList);
} else if (fromDate != null) {
List<EntityExpr> thruList = new LinkedList<EntityExpr>();
EntityExpr thruExpr = EntityCondition.makeCondition("caThruDate", EntityOperator.GREATER_THAN, fromDate);
thruList.add(thruExpr);
EntityExpr thruExpr2 = EntityCondition.makeCondition("caThruDate", EntityOperator.EQUALS, null);
thruList.add(thruExpr2);
EntityConditionList<EntityExpr> thruExprList = EntityCondition.makeCondition(thruList, EntityOperator.OR);
exprList.add(thruExprList);
}
EntityConditionList<EntityCondition> assocExprList = EntityCondition.makeCondition(exprList, EntityOperator.AND);
List<GenericValue> relatedAssocs = null;
try {
relatedAssocs = EntityQuery.use(delegator).from(viewName).where(assocExprList).orderBy("caFromDate").queryList();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
for (int i=0; i < relatedAssocs.size(); i++) {
GenericValue a = relatedAssocs.get(i);
Debug.logVerbose(" contentId:" + a.get("contentId") + " To:" + a.get("caContentIdTo") + " fromDate:" + a.get("caFromDate") + " thruDate:" + a.get("caThruDate") + " AssocTypeId:" + a.get("caContentAssocTypeId"), null);
}
Map<String, Object> results = new HashMap<String, Object>();
results.put("entityList", relatedAssocs);
return results;
}
/*
* A service that returns a list of ContentAssocDataResourceViewFrom/To views that are
* associated with the passed in contentId. Other conditions are also applied, including:
* a list of contentAssocTypeIds or contentTypeIds that the result set views must match.
* A direction (From or To - case insensitive).
* From and thru dates or date strings.
* A mapKey value.
*/
public static Map<String, Object> getAssocAndContentAndDataResourceCache(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
List<String> assocTypes = UtilGenerics.checkList(context.get("assocTypes"));
String assocTypesString = (String)context.get("assocTypesString");
if (UtilValidate.isNotEmpty(assocTypesString)) {
List<String> lst = StringUtil.split(assocTypesString, "|");
if (assocTypes == null) {
assocTypes = new LinkedList<String>();
}
assocTypes.addAll(lst);
}
List<String> contentTypes = UtilGenerics.checkList(context.get("contentTypes"));
String contentTypesString = (String)context.get("contentTypesString");
if (UtilValidate.isNotEmpty(contentTypesString)) {
List<String> lst = StringUtil.split(contentTypesString, "|");
if (contentTypes == null) {
contentTypes = new LinkedList<String>();
}
contentTypes.addAll(lst);
}
Timestamp fromDate = (Timestamp)context.get("fromDate");
String fromDateStr = (String)context.get("fromDateStr");
String contentId = (String)context.get("contentId");
String direction = (String)context.get("direction");
String mapKey = (String)context.get("mapKey");
String contentAssocPredicateId = (String)context.get("contentAssocPredicateId");
Boolean nullThruDatesOnly = (Boolean)context.get("nullThruDatesOnly");
Map<String, Object> results = null;
try {
results = getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, mapKey, direction, fromDate, fromDateStr, assocTypes, contentTypes, nullThruDatesOnly, contentAssocPredicateId, null);
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
} catch (MiniLangException e2) {
return ServiceUtil.returnError(e2.getMessage());
}
return results;
}
public static Map<String, Object> getAssocAndContentAndDataResourceCacheMethod(Delegator delegator, String contentId, String mapKey, String direction,
Timestamp fromDate, String fromDateStr, List<String> assocTypes, List<String> contentTypes, Boolean nullThruDatesOnly, String contentAssocPredicateId, String orderBy) throws GenericEntityException, MiniLangException {
EntityExpr joinExpr = null;
String viewName = null;
String contentFieldName = null;
if (direction != null && direction.equalsIgnoreCase("From")) {
contentFieldName = "caContentIdTo";
joinExpr = EntityCondition.makeCondition("caContentIdTo", EntityOperator.EQUALS, contentId);
} else {
contentFieldName = "caContentId";
joinExpr = EntityCondition.makeCondition("contentId", EntityOperator.EQUALS, contentId);
}
if (direction != null && direction.equalsIgnoreCase("From")) {
viewName = "ContentAssocDataResourceViewFrom";
} else {
viewName = "ContentAssocDataResourceViewTo";
}
List<EntityCondition> conditionList = new ArrayList<EntityCondition>();
conditionList.add(joinExpr);
if (UtilValidate.isNotEmpty(mapKey)) {
String mapKeyValue = "is null".equalsIgnoreCase(mapKey) ? null : mapKey;
conditionList.add(EntityCondition.makeCondition("caMapKey", mapKeyValue));
}
if (UtilValidate.isNotEmpty(contentAssocPredicateId)) {
String contentAssocPredicateIdValue = "is null".equalsIgnoreCase(contentAssocPredicateId) ? null : contentAssocPredicateId;
conditionList.add(EntityCondition.makeCondition("caMapKey", contentAssocPredicateIdValue));
}
if (nullThruDatesOnly != null && nullThruDatesOnly) {
conditionList.add(EntityCondition.makeCondition("caThruDate", null));
}
if (UtilValidate.isNotEmpty(assocTypes)) {
conditionList.add(EntityCondition.makeCondition("caContentAssocTypeId", EntityOperator.IN, assocTypes));
}
if (fromDate == null && fromDateStr != null) {
fromDate = UtilDateTime.toTimestamp(fromDateStr);
}
List<GenericValue> contentAssocsTypeFiltered = EntityQuery.use(delegator).from(viewName)
.where(conditionList).orderBy("caSequenceNum", "-caFromDate").cache().queryList();
String assocRelationName = null;
if (direction != null && direction.equalsIgnoreCase("To")) {
assocRelationName = "ToContent";
} else {
assocRelationName = "FromContent";
}
GenericValue contentAssocDataResourceView = null;
GenericValue content = null;
GenericValue dataResource = null;
List<GenericValue> contentAssocDataResourceList = new LinkedList<GenericValue>();
Locale locale = Locale.getDefault(); // TODO: this needs to be passed in
try{
for (GenericValue contentAssocView : contentAssocsTypeFiltered) {
GenericValue contentAssoc = EntityQuery.use(delegator).from("ContentAssoc").where(UtilMisc.toMap("contentId", contentAssocView.getString("contentId"),
"contentIdTo", contentAssocView.getString(contentFieldName), "contentAssocTypeId", contentAssocView.getString("caContentAssocTypeId"),
"fromDate", contentAssocView.getTimestamp("caFromDate"))).queryOne();
content = contentAssoc.getRelatedOne(assocRelationName, true);
if (UtilValidate.isNotEmpty(contentTypes)) {
String contentTypeId = (String)content.get("contentTypeId");
if (contentTypes.contains(contentTypeId)) {
contentAssocDataResourceView = delegator.makeValue(viewName);
contentAssocDataResourceView.setAllFields(content, true, null, null);
}
} else {
contentAssocDataResourceView = delegator.makeValue(viewName);
contentAssocDataResourceView.setAllFields(content, true, null, null);
}
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocOut", contentAssoc, contentAssocDataResourceView, new LinkedList<Object>(), locale);
String dataResourceId = content.getString("dataResourceId");
if (UtilValidate.isNotEmpty(dataResourceId))
dataResource = content.getRelatedOne("DataResource", true);
if (dataResource != null) {
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceOut", dataResource, contentAssocDataResourceView, new LinkedList<Object>(), locale);
}
contentAssocDataResourceList.add(contentAssocDataResourceView);
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (UtilValidate.isNotEmpty(orderBy)) {
List<String> orderByList = StringUtil.split(orderBy, "|");
contentAssocDataResourceList = EntityUtil.orderBy(contentAssocDataResourceList, orderByList);
}
Map<String, Object> results = new HashMap<String, Object>();
results.put("entityList", contentAssocDataResourceList);
if (UtilValidate.isNotEmpty(contentAssocDataResourceList)) {
results.put("view", contentAssocDataResourceList.get(0));
}
return results;
}
}
@@ -0,0 +1,162 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilCodec;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.common.UrlServletHelper;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.webapp.control.ContextFilter;
public class ContentUrlFilter extends ContextFilter {
public final static String module = ContentUrlFilter.class.getName();
public static final String CONTROL_MOUNT_POINT = "control";
protected static String defaultLocaleString = null;
protected static String redirectUrl = null;
public static String defaultViewRequest = "contentViewInfo";
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
Delegator delegator = (Delegator) httpRequest.getSession().getServletContext().getAttribute("delegator");
//Get ServletContext
ServletContext servletContext = config.getServletContext();
ContextFilter.setCharacterEncoding(request);
//Set request attribute and session
UrlServletHelper.setRequestAttributes(request, delegator, servletContext);
String urlContentId = null;
String pathInfo = UtilHttp.getFullRequestUrl(httpRequest);
if (UtilValidate.isNotEmpty(pathInfo)) {
String alternativeUrl = pathInfo.substring(pathInfo.lastIndexOf("/"));
if (alternativeUrl.endsWith("-content")) {
try {
GenericValue contentDataResourceView = EntityQuery.use(delegator).from("ContentDataResourceView")
.where("drObjectInfo", alternativeUrl)
.orderBy("createdDate DESC").queryFirst();
if (contentDataResourceView != null) {
GenericValue content = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentAssocTypeId", "ALTERNATIVE_URL",
"contentIdTo", contentDataResourceView.get("contentId"))
.filterByDate().queryFirst();
if (content != null) {
urlContentId = content.getString("contentId");
}
}
} catch (Exception e) {
Debug.logWarning(e.getMessage(), module);
}
}
if (UtilValidate.isNotEmpty(urlContentId)) {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append("/" + CONTROL_MOUNT_POINT);
urlBuilder.append("/" + config.getInitParameter("viewRequest") + "?contentId=" + urlContentId);
ContextFilter.setAttributesFromRequestBody(request);
//Set view query parameters
UrlServletHelper.setViewQueryParameters(request, urlBuilder);
Debug.logInfo("[Filtered request]: " + pathInfo + " (" + urlBuilder + ")", module);
RequestDispatcher dispatch = request.getRequestDispatcher(urlBuilder.toString());
dispatch.forward(request, response);
return;
}
//Check path alias
UrlServletHelper.checkPathAlias(request, httpResponse, delegator, pathInfo);
}
// we're done checking; continue on
chain.doFilter(request, response);
}
public static String makeContentAltUrl(HttpServletRequest request, HttpServletResponse response, String contentId, String viewContent) {
if (UtilValidate.isEmpty(contentId)) {
return null;
}
Delegator delegator = (Delegator) request.getAttribute("delegator");
String url = null;
try {
GenericValue contentAssocDataResource = EntityQuery.use(delegator)
.select("contentIdStart", "drObjectInfo", "dataResourceId", "caFromDate", "caThruDate", "caCreatedDate")
.from("ContentAssocDataResourceViewTo")
.where("caContentAssocTypeId", "ALTERNATIVE_URL",
"caThruDate", null,
"contentIdStart", contentId)
.orderBy("-caFromDate")
.queryFirst();
if (contentAssocDataResource != null) {
url = contentAssocDataResource.getString("drObjectInfo");
url = UtilCodec.getDecoder("url").decode(url);
String mountPoint = request.getContextPath();
if (!(mountPoint.equals("/")) && !(mountPoint.equals(""))) {
url = mountPoint + url;
}
}
} catch (Exception e) {
Debug.logWarning("[Exception] : " + e.getMessage(), module);
}
if (UtilValidate.isEmpty(url)) {
if (UtilValidate.isEmpty(viewContent)) {
viewContent = defaultViewRequest;
}
url = makeContentUrl(request, response, contentId, viewContent);
}
return url;
}
public static String makeContentUrl(HttpServletRequest request, HttpServletResponse response, String contentId, String viewContent) {
if (UtilValidate.isEmpty(contentId)) {
return null;
}
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(request.getSession().getServletContext().getContextPath());
if (urlBuilder.length() == 0 || urlBuilder.charAt(urlBuilder.length() - 1) != '/') {
urlBuilder.append("/");
}
urlBuilder.append(CONTROL_MOUNT_POINT);
if (UtilValidate.isNotEmpty(viewContent)) {
urlBuilder.append("/" + viewContent);
} else {
urlBuilder.append("/" + defaultViewRequest);
}
urlBuilder.append("?contentId=" + contentId);
return urlBuilder.toString();
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,31 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import org.ofbiz.base.util.StringUtil;
/**
* ContentWrapper Interface
*/
public interface ContentWrapper {
public StringUtil.StringWrapper get(String contentTypeId, String encoderType);
}
@@ -0,0 +1,313 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.entity.GenericValue;
/**
* PermissionRecorder Class
*
* Services for granting operation permissions on Content entities in a data-driven manner.
*/
public class PermissionRecorder {
public static final int PRE_PURPOSE = 0;
public static final int PRE_ROLE = 1;
public static final int WITH_ROLES = 2;
protected boolean isOn = false;
protected GenericValue userLogin;
protected List<Map<String, Object>> permCheckResults = new LinkedList<Map<String,Object>>();
protected boolean entityPermCheckResult = false;
protected String currentContentId = "";
protected Map<String, Object> currentContentMap;
protected String privilegeEnumId;
protected int currentCheckMode;
protected GenericValue [] contentPurposeOperations;
protected String [] statusTargets;
protected String [] targetOperations;
public static final String module = PermissionRecorder.class.getName();
public static final String [] opFields = { "contentPurposeTypeId", "contentOperationId", "roleTypeId", "statusId", "privilegeEnumId"};
public static final String [] fieldTitles = { "Purpose", "Operation", "Role", "Status", "Privilege"};
public PermissionRecorder() {
isOn = UtilProperties.propertyValueEqualsIgnoreCase("content", "permissionRecorderOn", "true");
}
public void setCheckMode(int val) {
currentCheckMode = val;
}
public int getCheckMode() {
return currentCheckMode;
}
public boolean isOn() {
return isOn;
}
public void setOn(boolean b) {
isOn = b;
}
public void setUserLogin(GenericValue user) {
userLogin = user;
}
public GenericValue getUserLogin() {
return userLogin;
}
public boolean getEntityPermCheckResult() {
return entityPermCheckResult;
}
public void setEntityPermCheckResult(boolean b) {
entityPermCheckResult = b;
}
public GenericValue [] getContentPurposeOperations() {
return contentPurposeOperations;
}
public void setContentPurposeOperations(List<GenericValue> opList) {
contentPurposeOperations = opList.toArray(new GenericValue[opList.size()]);
}
public void setPrivilegeEnumId(String id) {
privilegeEnumId = id;
}
public String getPrivilegeEnumId() {
return privilegeEnumId;
}
public String [] getStatusTargets() {
return statusTargets;
}
public void setStatusTargets(List<String> opList) {
statusTargets = opList.toArray(new String[opList.size()]);
}
public String [] getTargetOperations() {
return targetOperations;
}
public void setTargetOperations(List<String> opList) {
targetOperations = opList.toArray(new String[opList.size()]);
}
public void setCurrentContentId(String id) {
if (!currentContentId.equals(id)) {
currentContentMap = new HashMap<String, Object>();
permCheckResults.add(currentContentMap);
currentContentMap.put("contentId", id);
currentContentMap.put("checkResults", new LinkedList());
}
currentContentId = id;
}
public String getCurrentContentId() {
return currentContentId;
}
public void setRoles(List<String> roles) {
if (currentContentMap != null) {
if (roles != null)
currentContentMap.put("roles", roles.toArray());
else
currentContentMap.put("roles", null);
}
}
public void setPurposes(List<String> purposes) {
if (currentContentMap != null) {
if (purposes != null)
currentContentMap.put("purposes", purposes.toArray());
else
currentContentMap.put("purposes", null);
}
}
public void startMatchGroup(List<String> targetOperations, List<String> purposes, List<String> roles, List<String> targStatusList, String targPrivilegeEnumId, String contentId) {
currentContentMap = new HashMap<String, Object>();
permCheckResults.add(currentContentMap);
String s = null;
if (targetOperations != null) {
//if (Debug.infoOn()) Debug.logInfo("startMatchGroup, targetOperations:" + targetOperations, module);
s = targetOperations.toString();
//if (Debug.infoOn()) Debug.logInfo("startMatchGroup, targetOperations(string):" + s, module);
currentContentMap.put("contentOperationId", s);
}
if (purposes != null) {
//if (Debug.infoOn()) Debug.logInfo("startMatchGroup, purposes:" + purposes, module);
s = purposes.toString();
//if (Debug.infoOn()) Debug.logInfo("startMatchGroup, purposes(string):" + s, module);
currentContentMap.put("contentPurposeTypeId", s);
}
if (roles != null) {
//if (Debug.infoOn()) Debug.logInfo("startMatchGroup, roles:" + roles, module);
s = roles.toString();
//if (Debug.infoOn()) Debug.logInfo("startMatchGroup, roles(string):" + s, module);
currentContentMap.put("roleTypeId", s);
}
if (targStatusList != null) {
//if (Debug.infoOn()) Debug.logInfo("startMatchGroup, targStatusList:" + targStatusList, module);
s = targStatusList.toString();
//if (Debug.infoOn()) Debug.logInfo("startMatchGroup, targStatusList(string):" + s, module);
currentContentMap.put("statusId", s);
}
List<Map<String, Object>> checkResultList = new LinkedList<Map<String,Object>>();
currentContentMap.put("privilegeEnumId", privilegeEnumId);
currentContentMap.put("contentId", contentId);
currentContentMap.put("checkResultList", checkResultList);
currentContentMap.put("matches", null);
currentContentId = contentId;
//if (Debug.infoOn()) Debug.logInfo("startMatchGroup, currentContentMap:" + currentContentMap, module);
}
public void record(GenericValue purposeOp, boolean targetOpCond, boolean purposeCond, boolean statusCond, boolean privilegeCond, boolean roleCond) {
Map<String, Object> map = UtilMisc.makeMapWritable(purposeOp);
map.put("contentOperationIdCond", Boolean.valueOf(targetOpCond));
map.put("contentPurposeTypeIdCond", Boolean.valueOf(purposeCond));
map.put("statusIdCond", Boolean.valueOf(statusCond));
map.put("privilegeEnumIdCond", Boolean.valueOf(privilegeCond));
map.put("roleTypeIdCond", Boolean.valueOf(roleCond));
map.put("contentId", currentContentId);
List<Map<String, Object>> checkResultList = UtilGenerics.checkList(currentContentMap.get("checkResultList"));
checkResultList.add(map);
//if (Debug.infoOn()) Debug.logInfo("record, map:" + map, module);
}
public String toHtml() {
StringBuilder sb = new StringBuilder();
sb.append("<style type=\"text/css\">");
sb.append(".pass {background-color:lime; font-family:Verdana,Arial,sans-serif; font-size:10px; }");
sb.append(".fail {background-color:red; font-family:Verdana,Arial,sans-serif; font-size:10px; }");
sb.append(".target {background-color:lightgrey; font-family:Verdana,Arial,sans-serif; font-size:10px; }");
sb.append(".headr {background-color:white; font-weight:bold; font-family:Verdana,Arial,sans-serif; font-size:12px; }");
sb.append("</style>");
//if (Debug.infoOn()) Debug.logInfo("toHtml, style:" + sb.toString(), module);
sb.append("<table border=\"1\" >");
// Do header row
sb.append("<tr>");
sb.append("<td class=\"headr\">");
sb.append("Content Id");
sb.append("</td>");
//if (Debug.infoOn()) Debug.logInfo("renderResultRowHtml, (1):" + sb.toString(), module);
for (int i=0; i < fieldTitles.length; i++) {
String opField = fieldTitles[i];
sb.append("<td class=\"headr\">");
sb.append(opField);
sb.append("</td>");
}
sb.append("<td class=\"headr\" >Pass/Fail</td>");
sb.append("</tr>");
for (Map<String, Object> cMap : permCheckResults) {
sb.append(renderCurrentContentMapHtml(cMap));
}
sb.append("</table>");
return sb.toString();
}
public String renderCurrentContentMapHtml(Map<String, Object> cMap) {
StringBuilder sb = new StringBuilder();
List<Map<String, Object>> resultList = UtilGenerics.checkList(cMap.get("checkResultList"));
for (Map<String, Object> rMap : resultList) {
//if (Debug.infoOn()) Debug.logInfo("renderCCMapHtml, (1):" + rMap, module);
sb.append(renderResultRowHtml(rMap, cMap));
}
return sb.toString();
}
//public static final String [] opFields = { "contentPurposeTypeId", "contentOperationId", "roleTypeId", "statusId", "privilegeEnumId"};
public String renderResultRowHtml(Map<String, Object> rMap, Map<String, Object> currentContentResultMap) {
StringBuilder sb = new StringBuilder();
// Do target row
sb.append("<tr>");
sb.append("<td class=\"target\">");
sb.append((String)rMap.get("contentId"));
sb.append("</td>");
//if (Debug.infoOn()) Debug.logInfo("renderResultRowHtml, (1):" + sb.toString(), module);
String str = null;
String s = null;
for (int i=0; i < opFields.length; i++) {
String opField = opFields[i];
sb.append("<td class=\"target\">");
s = (String)currentContentResultMap.get(opField);
if (s != null)
str = s;
else
str = "&nbsp;";
sb.append(str);
sb.append("</td>");
}
sb.append("<td class=\"target\" >&nbsp;</td>");
sb.append("</tr>");
//if (Debug.infoOn()) Debug.logInfo("renderResultRowHtml, (2):" + sb.toString(), module);
// Do UUT row
sb.append("<tr>");
sb.append("<td class=\"target\">");
sb.append((String)currentContentResultMap.get("contentId"));
sb.append("</td>");
boolean isPass = true;
for (int i=0; i < opFields.length; i++) {
String opField = opFields[i];
Boolean bool = (Boolean)rMap.get(opField + "Cond");
String cls = (bool.booleanValue()) ? "pass" : "fail";
if (!bool.booleanValue())
isPass = false;
sb.append("<td class=\"" + cls + "\">");
//if (Debug.infoOn()) Debug.logInfo("renderResultRowHtml, (2b):" + sb.toString(), module);
s = (String)rMap.get(opField);
//if (Debug.infoOn()) Debug.logInfo("renderResultRowHtml, (s):" + s, module);
sb.append(s);
sb.append("</td>");
}
String passFailCls = (isPass) ? "pass" : "fail";
sb.append("<td class=\"" + passFailCls +"\">" + passFailCls.toUpperCase() + "</td>");
sb.append("</tr>");
//if (Debug.infoOn()) Debug.logInfo("renderResultRowHtml, (3):" + sb.toString(), module);
return sb.toString();
}
}
@@ -0,0 +1,571 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.content;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.FileUtil;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.model.ModelEntity;
import org.ofbiz.entity.transaction.GenericTransactionException;
import org.ofbiz.entity.transaction.TransactionUtil;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.minilang.MiniLangException;
import org.ofbiz.minilang.SimpleMapProcessor;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceAuthException;
import org.ofbiz.service.ServiceUtil;
/**
* UploadContentAndImage Class
*
* Services for granting operation permissions on Content entities in a data-driven manner.
*/
public class UploadContentAndImage {
public static final String module = UploadContentAndImage.class.getName();
public static final String err_resource = "ContentErrorUiLabels";
public UploadContentAndImage() {}
public static String uploadContentAndImage(HttpServletRequest request, HttpServletResponse response) {
try {
Locale locale = UtilHttp.getLocale(request);
LocalDispatcher dispatcher = (LocalDispatcher)request.getAttribute("dispatcher");
Delegator delegator = (Delegator) request.getAttribute("delegator");
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
ServletFileUpload dfu = new ServletFileUpload(new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
List<FileItem> lst = null;
try {
lst = UtilGenerics.checkList(dfu.parseRequest(request));
} catch (FileUploadException e4) {
request.setAttribute("_ERROR_MESSAGE_", e4.getMessage());
Debug.logError("[UploadContentAndImage.uploadContentAndImage] " + e4.getMessage(), module);
return "error";
}
//if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]lst " + lst, module);
if (lst.size() == 0) {
String errMsg = UtilProperties.getMessage(UploadContentAndImage.err_resource, "uploadContentAndImage.no_files_uploaded", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
return "error";
}
Map<String, Object> passedParams = new HashMap<String, Object>();
FileItem fi = null;
FileItem imageFi = null;
byte[] imageBytes = {};
for (int i = 0; i < lst.size(); i++) {
fi = lst.get(i);
//String fn = fi.getName();
String fieldName = fi.getFieldName();
if (fi.isFormField()) {
String fieldStr = fi.getString();
passedParams.put(fieldName, fieldStr);
} else if (fieldName.equals("imageData")) {
imageFi = fi;
imageBytes = imageFi.get();
}
}
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module);
}
TransactionUtil.begin();
List<String> contentPurposeList = ContentWorker.prepContentPurposeList(passedParams);
passedParams.put("contentPurposeList", contentPurposeList);
String entityOperation = (String)passedParams.get("entityOperation");
String passedContentId = (String)passedParams.get("ftlContentId");
List<String> targetOperationList = ContentWorker.prepTargetOperationList(passedParams, entityOperation);
passedParams.put("targetOperationList", targetOperationList);
// Create or update FTL template
Map<String, Object> ftlContext = new HashMap<String, Object>();
ftlContext.put("userLogin", userLogin);
ftlContext.put("contentId", passedParams.get("ftlContentId"));
ftlContext.put("ownerContentId", passedParams.get("ownerContentId"));
String contentTypeId = (String)passedParams.get("contentTypeId");
ftlContext.put("contentTypeId", contentTypeId);
ftlContext.put("statusId", passedParams.get("statusId"));
ftlContext.put("contentPurposeList", UtilMisc.toList(passedParams.get("contentPurposeList")));
ftlContext.put("contentPurposeList", contentPurposeList);
ftlContext.put("targetOperationList",targetOperationList);
ftlContext.put("contentName", passedParams.get("contentName"));
ftlContext.put("dataTemplateTypeId", passedParams.get("dataTemplateTypeId"));
ftlContext.put("description", passedParams.get("description"));
ftlContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
String drid = (String)passedParams.get("dataResourceId");
//if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]drid:" + drid, module);
ftlContext.put("dataResourceId", drid);
ftlContext.put("dataResourceTypeId", null); // inhibits persistence of DataResource, because it already exists
String contentIdTo = (String)passedParams.get("contentIdTo");
ftlContext.put("contentIdTo", contentIdTo);
String contentAssocTypeId = (String)passedParams.get("contentAssocTypeId");
ftlContext.put("contentAssocTypeId", null); // Don't post assoc at this time
Map<String, Object> ftlResults = dispatcher.runSync("persistContentAndAssoc", ftlContext);
boolean isError = ModelService.RESPOND_ERROR.equals(ftlResults.get(ModelService.RESPONSE_MESSAGE));
if (isError) {
request.setAttribute("_ERROR_MESSAGE_", ftlResults.get(ModelService.ERROR_MESSAGE));
TransactionUtil.rollback();
return "error";
}
String ftlContentId = (String)ftlResults.get("contentId");
if (UtilValidate.isNotEmpty(contentIdTo)) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("fromDate", UtilDateTime.nowTimestamp());
map.put("contentId", ftlContentId);
map.put("contentIdTo", contentIdTo);
map.put("userLogin", userLogin);
if (UtilValidate.isEmpty(contentAssocTypeId) && UtilValidate.isEmpty(passedContentId) && UtilValidate.isNotEmpty(contentIdTo)) {
// switch the association order because we are really not linking to the forum
// but showing that this content is released to that forum.
map.put("contentIdTo", ftlContentId);
map.put("contentId", contentIdTo);
map.put("contentAssocTypeId", "PUBLISH_RELEASE");
} else if (contentAssocTypeId.equals("PUBLISH_LINK")) {
map.put("contentAssocTypeId", "PUBLISH_LINK");
String publishOperation = (String)passedParams.get("publishOperation");
if (UtilValidate.isEmpty(publishOperation)) {
publishOperation = "CONTENT_PUBLISH";
}
map.put("targetOperationList", StringUtil.split(publishOperation, "|"));
map.put("targetOperationString", null);
} else {
map.put("contentAssocTypeId", contentAssocTypeId);
}
if (UtilValidate.isNotEmpty(map.get("contentAssocTypeId"))) {
ftlResults = dispatcher.runSync("createContentAssoc", map);
isError = ModelService.RESPOND_ERROR.equals(ftlResults.get(ModelService.RESPONSE_MESSAGE));
if (isError) {
request.setAttribute("_ERROR_MESSAGE_", ftlResults.get(ModelService.ERROR_MESSAGE));
TransactionUtil.rollback();
return "error";
}
}
}
if (UtilValidate.isEmpty(ftlContentId)) {
ftlContentId = passedContentId;
}
String ftlDataResourceId = drid;
if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]ftlContentId:" + ftlContentId, module);
//if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]ftlDataResourceId:" + ftlDataResourceId, module);
// Create or update summary text subContent
if (passedParams.containsKey("summaryData")) {
Map<String, Object> sumContext = new HashMap<String, Object>();
sumContext.put("userLogin", userLogin);
sumContext.put("contentId", passedParams.get("sumContentId"));
sumContext.put("ownerContentId", ftlContentId);
sumContext.put("contentTypeId", "DOCUMENT");
sumContext.put("statusId", passedParams.get("statusId"));
sumContext.put("contentPurposeList", UtilMisc.toList("SUMMARY"));
//sumContext.put("contentPurposeList", contentPurposeList);
sumContext.put("targetOperationList",targetOperationList);
sumContext.put("contentName", passedParams.get("contentName"));
sumContext.put("description", passedParams.get("description"));
sumContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
sumContext.put("dataResourceId", passedParams.get("sumDataResourceId"));
sumContext.put("dataResourceTypeId", "ELECTRONIC_TEXT");
sumContext.put("contentIdTo", ftlContentId);
sumContext.put("contentAssocTypeId", "SUB_CONTENT");
sumContext.put("textData", passedParams.get("summaryData"));
sumContext.put("mapKey", "SUMMARY");
sumContext.put("dataTemplateTypeId", "NONE");
Map<String, Object> sumResults = dispatcher.runSync("persistContentAndAssoc", sumContext);
isError = ModelService.RESPOND_ERROR.equals(sumResults.get(ModelService.RESPONSE_MESSAGE));
if (isError) {
request.setAttribute("_ERROR_MESSAGE_", sumResults.get(ModelService.ERROR_MESSAGE));
TransactionUtil.rollback();
return "error";
}
}
// Create or update electronic text subContent
if (passedParams.containsKey("textData")) {
Map<String, Object> txtContext = new HashMap<String, Object>();
txtContext.put("userLogin", userLogin);
txtContext.put("contentId", passedParams.get("txtContentId"));
txtContext.put("ownerContentId", ftlContentId);
txtContext.put("contentTypeId", "DOCUMENT");
txtContext.put("statusId", passedParams.get("statusId"));
//txtContext.put("contentPurposeList", contentPurposeList);
txtContext.put("contentPurposeList", UtilMisc.toList("MAIN_ARTICLE"));
txtContext.put("targetOperationList",targetOperationList);
txtContext.put("contentName", passedParams.get("contentName"));
txtContext.put("description", passedParams.get("description"));
txtContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
txtContext.put("dataResourceId", passedParams.get("txtDataResourceId"));
txtContext.put("dataResourceTypeId", "ELECTRONIC_TEXT");
txtContext.put("contentIdTo", ftlContentId);
txtContext.put("contentAssocTypeId", "SUB_CONTENT");
txtContext.put("textData", passedParams.get("textData"));
txtContext.put("mapKey", "ARTICLE");
txtContext.put("dataTemplateTypeId", "NONE");
Map<String, Object> txtResults = dispatcher.runSync("persistContentAndAssoc", txtContext);
isError = ModelService.RESPOND_ERROR.equals(txtResults.get(ModelService.RESPONSE_MESSAGE));
if (isError) {
request.setAttribute("_ERROR_MESSAGE_", txtResults.get(ModelService.ERROR_MESSAGE));
TransactionUtil.rollback();
return "error";
}
}
// Create or update image subContent
Map<String, Object> imgContext = new HashMap<String, Object>();
if (imageBytes.length > 0) {
imgContext.put("userLogin", userLogin);
imgContext.put("contentId", passedParams.get("imgContentId"));
imgContext.put("ownerContentId", ftlContentId);
imgContext.put("contentTypeId", "DOCUMENT");
imgContext.put("statusId", passedParams.get("statusId"));
imgContext.put("contentName", passedParams.get("contentName"));
imgContext.put("description", passedParams.get("description"));
imgContext.put("contentPurposeList", contentPurposeList);
imgContext.put("privilegeEnumId", passedParams.get("privilegeEnumId"));
imgContext.put("targetOperationList",targetOperationList);
imgContext.put("dataResourceId", passedParams.get("imgDataResourceId"));
//String dataResourceTypeId = (String)passedParams.get("dataResourceTypeId");
//if (UtilValidate.isEmpty(dataResourceTypeId))
//dataResourceTypeId = "IMAGE_OBJECT";
String dataResourceTypeId = "IMAGE_OBJECT";
imgContext.put("dataResourceTypeId", dataResourceTypeId);
imgContext.put("contentIdTo", ftlContentId);
imgContext.put("contentAssocTypeId", "SUB_CONTENT");
imgContext.put("imageData", imageBytes);
imgContext.put("mapKey", "IMAGE");
imgContext.put("dataTemplateTypeId", "NONE");
// String rootDir = request.getSession().getServletContext().getRealPath("/");
imgContext.put("rootDir", "rootDir");
if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]imgContext " + imgContext, module);
Map<String, Object> imgResults = dispatcher.runSync("persistContentAndAssoc", imgContext);
isError = ModelService.RESPOND_ERROR.equals(imgResults.get(ModelService.RESPONSE_MESSAGE));
if (isError) {
request.setAttribute("_ERROR_MESSAGE_", imgResults.get(ModelService.ERROR_MESSAGE));
TransactionUtil.rollback();
return "error";
}
}
// Check for existing AUTHOR link
String userLoginId = userLogin.getString("userLoginId");
GenericValue authorContent = EntityQuery.use(delegator).from("Content").where("contentId", userLoginId).cache().queryOne();
if (authorContent != null) {
long currentAuthorAssocCount = EntityQuery.use(delegator).from("ContentAssoc")
.where("contentId", ftlContentId, "contentIdTo", userLoginId, "contentAssocTypeId", "AUTHOR")
.filterByDate().queryCount();
//if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]currentAuthorAssocList " + currentAuthorAssocList, module);
if (currentAuthorAssocCount == 0) {
// Don't want to bother with permission checking on this association
GenericValue authorAssoc = delegator.makeValue("ContentAssoc");
authorAssoc.set("contentId", ftlContentId);
authorAssoc.set("contentIdTo", userLoginId);
authorAssoc.set("contentAssocTypeId", "AUTHOR");
authorAssoc.set("fromDate", UtilDateTime.nowTimestamp());
authorAssoc.set("createdByUserLogin", userLoginId);
authorAssoc.set("lastModifiedByUserLogin", userLoginId);
authorAssoc.set("createdDate", UtilDateTime.nowTimestamp());
authorAssoc.set("lastModifiedDate", UtilDateTime.nowTimestamp());
authorAssoc.create();
}
}
request.setAttribute("dataResourceId", ftlDataResourceId);
request.setAttribute("drDataResourceId", ftlDataResourceId);
request.setAttribute("contentId", ftlContentId);
request.setAttribute("masterContentId", ftlContentId);
request.setAttribute("contentIdTo", contentIdTo);
String newTrail = passedParams.get("nodeTrailCsv") + "," + ftlContentId;
request.setAttribute("nodeTrailCsv", newTrail);
request.setAttribute("passedParams", passedParams);
//if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]newTrail: " + newTrail, module);
TransactionUtil.commit();
} catch (Exception e) {
Debug.logError(e, "[UploadContentAndImage] " , module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
try {
TransactionUtil.rollback();
} catch (GenericTransactionException e2) {
request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
return "error";
}
return "error";
}
return "success";
}
public static String uploadContentStuff(HttpServletRequest request, HttpServletResponse response) {
try {
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
ServletFileUpload dfu = new ServletFileUpload(new DiskFileItemFactory(10240, FileUtil.getFile("runtime/tmp")));
//if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]DiskFileUpload " + dfu, module);
List<FileItem> lst = null;
try {
lst = UtilGenerics.checkList(dfu.parseRequest(request));
} catch (FileUploadException e4) {
request.setAttribute("_ERROR_MESSAGE_", e4.getMessage());
Debug.logError("[UploadContentAndImage.uploadContentAndImage] " + e4.getMessage(), module);
return "error";
}
//if (Debug.infoOn()) Debug.logInfo("[UploadContentAndImage]lst " + lst, module);
if (lst.size() == 0) {
request.setAttribute("_ERROR_MESSAGE_", "No files uploaded");
Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
return "error";
}
Map<String, Object> passedParams = new HashMap<String, Object>();
FileItem fi = null;
FileItem imageFi = null;
byte[] imageBytes = {};
passedParams.put("userLogin", userLogin);
for (int i = 0; i < lst.size(); i++) {
fi = lst.get(i);
//String fn = fi.getName();
String fieldName = fi.getFieldName();
if (fi.isFormField()) {
String fieldStr = fi.getString();
passedParams.put(fieldName, fieldStr);
} else if (fieldName.startsWith("imageData")) {
imageFi = fi;
String fileName = fi.getName();
passedParams.put("drObjectInfo", fileName);
String contentType = fi.getContentType();
passedParams.put("drMimeTypeId", contentType);
imageBytes = imageFi.get();
passedParams.put(fieldName, imageBytes);
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentAndImage]imageData: " + imageBytes.length, module);
}
}
}
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentAndImage]passedParams: " + passedParams, module);
}
// The number of multi form rows is retrieved
int rowCount = UtilHttp.getMultiFormRowCount(request);
if (rowCount < 1) {
rowCount = 1;
}
TransactionUtil.begin();
for (int i=0; i < rowCount; i++) {
String suffix = "_o_" + i;
if (i==0) {
suffix = "";
}
String returnMsg = processContentUpload(passedParams, suffix, request);
if (returnMsg.equals("error")) {
try {
TransactionUtil.rollback();
} catch (GenericTransactionException e2) {
ServiceUtil.setMessages(request, e2.getMessage(), null, null);
return "error";
}
return "error";
}
}
TransactionUtil.commit();
} catch (Exception e) {
Debug.logError(e, "[UploadContentAndImage] " , module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
try {
TransactionUtil.rollback();
} catch (GenericTransactionException e2) {
request.setAttribute("_ERROR_MESSAGE_", e2.getMessage());
return "error";
}
return "error";
}
return "success";
}
public static String processContentUpload(Map<String, Object> passedParams, String suffix, HttpServletRequest request) throws GenericServiceException {
LocalDispatcher dispatcher = (LocalDispatcher)request.getAttribute("dispatcher");
Delegator delegator = (Delegator)request.getAttribute("delegator");
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue)session.getAttribute("userLogin");
Map<String, Object> ftlContext = new HashMap<String, Object>();
String contentPurposeString = (String)passedParams.get("contentPurposeString" + suffix);
if (UtilValidate.isEmpty(contentPurposeString)) {
contentPurposeString = (String)passedParams.get("contentPurposeString");
}
List<String> contentPurposeList = StringUtil.split(contentPurposeString,"|");
ftlContext.put("contentPurposeList", contentPurposeList);
String targetOperationString = (String)passedParams.get("targetOperationString" + suffix);
if (UtilValidate.isEmpty(targetOperationString)) {
targetOperationString = (String)passedParams.get("targetOperationString");
}
List<String> targetOperationList = StringUtil.split(targetOperationString,"|");
ftlContext.put("targetOperationList",targetOperationList);
ftlContext.put("userLogin", userLogin);
Object objSequenceNum = passedParams.get("caSequenceNum");
if (objSequenceNum != null) {
if (objSequenceNum instanceof String) {
Long sequenceNum = null;
try {
sequenceNum = Long.valueOf((String)objSequenceNum);
} catch (NumberFormatException e) {}
passedParams.put("caSequenceNum", sequenceNum);
}
}
ModelEntity modelEntity = delegator.getModelEntity("ContentAssocDataResourceViewFrom");
List<String> fieldNames = modelEntity.getAllFieldNames();
Map<String, Object> ftlContext2 = new HashMap<String, Object>();
Map<String, Object> ftlContext3 = new HashMap<String, Object>();
for (String keyName : fieldNames) {
Object obj = passedParams.get(keyName + suffix);
ftlContext2.put(keyName, obj);
}
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentStuff]ftlContext2:" + ftlContext2, module);
}
List<Object> errorMessages = new LinkedList<Object>();
Locale loc = Locale.getDefault();
try {
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentIn", ftlContext2, ftlContext3, errorMessages, loc);
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentOut", ftlContext3, ftlContext, errorMessages, loc);
ftlContext3 = new HashMap<String, Object>();
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceIn", ftlContext2, ftlContext3, errorMessages, loc);
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceOut", ftlContext3, ftlContext, errorMessages, loc);
ftlContext3 = new HashMap<String, Object>();
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocIn", ftlContext2, ftlContext3, errorMessages, loc);
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocOut", ftlContext3, ftlContext, errorMessages, loc);
} catch (MiniLangException e) {
throw new GenericServiceException(e.getMessage());
}
ftlContext.put("textData", passedParams.get("textData" + suffix));
byte[] bytes = (byte[])passedParams.get("imageData" + suffix);
ftlContext.put("imageData", bytes);
//if (Debug.infoOn()) Debug.logInfo("[UploadContentStuff]byteBuffer:" + bytes, module);
//contentAssocDataResourceViewFrom.setAllFields(ftlContext2, true, null, null);
//ftlContext.putAll(ftlContext2);
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentStuff]ftlContext:" + ftlContext, module);
}
Map<String, Object> ftlResults = null;
try {
ftlResults = dispatcher.runSync("persistContentAndAssoc", ftlContext);
} catch (ServiceAuthException e) {
String msg = e.getMessage();
request.setAttribute("_ERROR_MESSAGE_", msg);
List<String> errorMsgList = UtilGenerics.checkList(request.getAttribute("_EVENT_MESSAGE_LIST_"));
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentStuff]errorMsgList:" + errorMsgList, module);
}
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentStuff]msg:" + msg, module);
}
if (errorMsgList == null) {
errorMsgList = new LinkedList<String>();
request.setAttribute("errorMessageList", errorMsgList);
}
errorMsgList.add(msg);
return "error";
}
String msg = ServiceUtil.getErrorMessage(ftlResults);
if (UtilValidate.isNotEmpty(msg)) {
request.setAttribute("_ERROR_MESSAGE_", msg);
List<String> errorMsgList = UtilGenerics.checkList(request.getAttribute("_EVENT_MESSAGE_LIST_"));
if (errorMsgList == null) {
errorMsgList = new LinkedList<String>();
request.setAttribute("errorMessageList", errorMsgList);
}
errorMsgList.add(msg);
return "error";
}
String returnedContentId = (String)ftlResults.get("contentId");
if (Debug.infoOn()) {
Debug.logInfo("returnedContentId:" + returnedContentId, module);
}
request.setAttribute("contentId" + suffix, ftlResults.get("contentId"));
request.setAttribute("caContentIdTo" + suffix, ftlResults.get("contentIdTo"));
request.setAttribute("caContentIdStart" + suffix, ftlResults.get("contentIdTo"));
request.setAttribute("caContentAssocTypeId" + suffix, ftlResults.get("contentAssocTypeId"));
request.setAttribute("caFromDate" + suffix, ftlResults.get("fromDate"));
request.setAttribute("drDataResourceId" + suffix, ftlResults.get("dataResourceId"));
request.setAttribute("caContentId" + suffix, ftlResults.get("contentId"));
String caContentIdTo = (String)passedParams.get("caContentIdTo");
if (UtilValidate.isNotEmpty(caContentIdTo)) {
Map<String, Object> resequenceContext = new HashMap<String, Object>();
resequenceContext.put("contentIdTo", caContentIdTo);
resequenceContext.put("userLogin", userLogin);
try {
ftlResults = dispatcher.runSync("resequence", resequenceContext);
} catch (ServiceAuthException e) {
msg = e.getMessage();
request.setAttribute("_ERROR_MESSAGE_", msg);
List<String> errorMsgList = UtilGenerics.checkList(request.getAttribute("_EVENT_MESSAGE_LIST_"));
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentStuff]errorMsgList:" + errorMsgList, module);
}
if (Debug.infoOn()) {
Debug.logInfo("[UploadContentStuff]msg:" + msg, module);
}
if (errorMsgList == null) {
errorMsgList = new LinkedList<String>();
request.setAttribute("errorMessageList", errorMsgList);
}
errorMsgList.add(msg);
return "error";
}
}
return "success";
}
} // end of UploadContentAndImage
@@ -0,0 +1,369 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.data;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.IOUtils;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtilProperties;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
/**
* DataEvents Class
*/
public class DataEvents {
public static final String module = DataEvents.class.getName();
public static final String err_resource = "ContentErrorUiLabels";
public static String uploadImage(HttpServletRequest request, HttpServletResponse response) {
return DataResourceWorker.uploadAndStoreImage(request, "dataResourceId", "imageData");
}
/** Streams any binary content data to the browser */
public static String serveObjectData(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
Locale locale = UtilHttp.getLocale(request);
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
String userAgent = request.getHeader("User-Agent");
Map<String, Object> httpParams = UtilHttp.getParameterMap(request);
String contentId = (String) httpParams.get("contentId");
if (UtilValidate.isEmpty(contentId)) {
String errorMsg = "Required parameter contentId not found!";
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
return "error";
}
// get the permission service required for streaming data; default is always the genericContentPermission
String permissionService = EntityUtilProperties.getPropertyValue("content", "stream.permission.service", "genericContentPermission", delegator);
// get the content record
GenericValue content;
try {
content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
// make sure content exists
if (content == null) {
String errorMsg = "No content found for Content ID: " + contentId;
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
return "error";
}
// make sure there is a DataResource for this content
String dataResourceId = content.getString("dataResourceId");
if (UtilValidate.isEmpty(dataResourceId)) {
String errorMsg = "No Data Resource found for Content ID: " + contentId;
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
return "error";
}
// get the data resource
GenericValue dataResource;
try {
dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
// make sure the data resource exists
if (dataResource == null) {
String errorMsg = "No Data Resource found for ID: " + dataResourceId;
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
return "error";
}
// see if data resource is public or not
String isPublic = dataResource.getString("isPublic");
if (UtilValidate.isEmpty(isPublic)) {
isPublic = "N";
}
// not public check security
if (!"Y".equalsIgnoreCase(isPublic)) {
// do security check
Map<String, ? extends Object> permSvcCtx = UtilMisc.toMap("userLogin", userLogin, "locale", locale, "mainAction", "VIEW", "contentId", contentId);
Map<String, Object> permSvcResp;
try {
permSvcResp = dispatcher.runSync(permissionService, permSvcCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
if (ServiceUtil.isError(permSvcResp)) {
String errorMsg = ServiceUtil.getErrorMessage(permSvcResp);
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
return "error";
}
// no service errors; now check the actual response
Boolean hasPermission = (Boolean) permSvcResp.get("hasPermission");
if (!hasPermission.booleanValue()) {
String errorMsg = (String) permSvcResp.get("failMessage");
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
return "error";
}
}
// get objects needed for data processing
String contextRoot = (String) request.getAttribute("_CONTEXT_ROOT_");
String webSiteId = (String) session.getAttribute("webSiteId");
String dataName = dataResource.getString("dataResourceName");
// get the mime type
String mimeType = DataResourceWorker.getMimeType(dataResource);
// hack for IE and mime types
if (userAgent.indexOf("MSIE") > -1) {
Debug.logInfo("Found MSIE changing mime type from - " + mimeType, module);
mimeType = "application/octet-stream";
}
// for local resources; use HTTPS if we are requested via HTTPS
String https = "false";
String protocol = request.getProtocol();
if ("https".equalsIgnoreCase(protocol)) {
https = "true";
}
// get the data resource stream and content length
Map<String, Object> resourceData;
try {
resourceData = DataResourceWorker.getDataResourceStream(dataResource, https, webSiteId, locale, contextRoot, false);
} catch (IOException e) {
Debug.logError(e, "Error getting DataResource stream", module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
} catch (GeneralException e) {
Debug.logError(e, "Error getting DataResource stream", module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
// get the stream data
InputStream stream = null;
Long length = null;
if (resourceData != null) {
stream = (InputStream) resourceData.get("stream");
length = (Long) resourceData.get("length");
}
Debug.logInfo("Got resource data stream: " + length + " bytes", module);
// stream the content to the browser
if (stream != null && length != null) {
try {
UtilHttp.streamContentToBrowser(response, stream, length.intValue(), mimeType, dataName);
} catch (IOException e) {
Debug.logError(e, "Unable to write content to browser", module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
// this must be handled with a special error string because the output stream has been already used and we will not be able to return the error page;
// the "io-error" should be associated to a response of type "none"
return "io-error";
}
} else {
String errorMsg = "No data is available.";
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
return "error";
}
return "success";
}
/** Streams ImageDataResource data to the output. */
// TODO: remove this method in favor of serveObjectData
public static String serveImage(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
ServletContext application = session.getServletContext();
Delegator delegator = (Delegator) request.getAttribute("delegator");
Map<String, Object> parameters = UtilHttp.getParameterMap(request);
Debug.logInfo("Img UserAgent - " + request.getHeader("User-Agent"), module);
String dataResourceId = (String) parameters.get("imgId");
if (UtilValidate.isEmpty(dataResourceId)) {
String errorMsg = "Error getting image record from db: " + " dataResourceId is empty";
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
return "error";
}
try {
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne();
if (!"Y".equals(dataResource.getString("isPublic"))) {
// now require login...
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
if (userLogin == null) {
String errorMsg = "You must be logged in to download the Data Resource with ID [" + dataResourceId + "]";
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
return "error";
}
// make sure the logged in user can download this content; otherwise is a pretty big security hole for DataResource records...
// TODO: should we restrict the roleTypeId?
long contentAndRoleCount = EntityQuery.use(delegator).from("ContentAndRole")
.where("partyId", userLogin.get("partyId"),
"dataResourceId", dataResourceId)
.queryCount();
if (contentAndRoleCount == 0) {
String errorMsg = "You do not have permission to download the Data Resource with ID [" + dataResourceId + "], ie you are not associated with it.";
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
return "error";
}
}
String mimeType = DataResourceWorker.getMimeType(dataResource);
// hack for IE and mime types
String userAgent = request.getHeader("User-Agent");
if (userAgent.indexOf("MSIE") > -1) {
Debug.logInfo("Found MSIE changing mime type from - " + mimeType, module);
mimeType = "application/octet-stream";
}
if (mimeType != null) {
response.setContentType(mimeType);
}
OutputStream os = response.getOutputStream();
Map<String, Object> resourceData = DataResourceWorker.getDataResourceStream(dataResource, "", application.getInitParameter("webSiteId"), UtilHttp.getLocale(request), application.getRealPath("/"), false);
os.write(IOUtils.toByteArray((ByteArrayInputStream)resourceData.get("stream")));
os.flush();
} catch (GenericEntityException e) {
String errMsg = "Error downloading digital product content: " + e.toString();
Debug.logError(e, errMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
} catch (GeneralException e) {
String errMsg = "Error downloading digital product content: " + e.toString();
Debug.logError(e, errMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
} catch (IOException e) {
String errMsg = "Error downloading digital product content: " + e.toString();
Debug.logError(e, errMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
return "success";
}
/** Dual create and edit event.
* Needed to make permission criteria available to services.
*/
public static String persistDataResource(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> result = null;
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
Delegator delegator = (Delegator) request.getAttribute("delegator");
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String dataResourceId = (String)paramMap.get("dataResourceId");
GenericValue dataResource = delegator.makeValue("DataResource");
dataResource.setPKFields(paramMap);
dataResource.setNonPKFields(paramMap);
Map<String, Object> serviceInMap = UtilMisc.makeMapWritable(dataResource);
serviceInMap.put("userLogin", userLogin);
String mode = (String)paramMap.get("mode");
Locale locale = UtilHttp.getLocale(request);
if (mode != null && mode.equals("UPDATE")) {
try {
result = dispatcher.runSync("updateDataResource", serviceInMap);
} catch (GenericServiceException e) {
String errMsg = UtilProperties.getMessage(DataEvents.err_resource, "dataEvents.error_call_update_service", locale);
String errorMsg = "Error calling the updateDataResource service." + e.toString();
Debug.logError(e, errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errMsg + e.toString());
return "error";
}
} else {
mode = "CREATE";
try {
result = dispatcher.runSync("createDataResource", serviceInMap);
} catch (GenericServiceException e) {
String errMsg = UtilProperties.getMessage(DataEvents.err_resource, "dataEvents.error_call_create_service", locale);
String errorMsg = "Error calling the createDataResource service." + e.toString();
Debug.logError(e, errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errMsg + e.toString());
return "error";
}
dataResourceId = (String)result.get("dataResourceId");
dataResource.set("dataResourceId", dataResourceId);
}
String returnStr = "success";
if (mode.equals("CREATE")) {
// Set up return message to guide selection of follow on view
request.setAttribute("dataResourceId", result.get("dataResourceId"));
String dataResourceTypeId = (String)serviceInMap.get("dataResourceTypeId");
if (dataResourceTypeId != null) {
if (dataResourceTypeId.equals("ELECTRONIC_TEXT")
|| dataResourceTypeId.equals("IMAGE_OBJECT")) {
returnStr = dataResourceTypeId;
}
}
}
return returnStr;
}
}
@@ -0,0 +1,684 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.data;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceUtil;
/**
* DataServices Class
*/
public class DataServices {
public static final String module = DataServices.class.getName();
public static final String resource = "ContentUiLabels";
public static Map<String, Object> clearAssociatedRenderCache(DispatchContext dctx, Map<String, Object> context) {
Delegator delegator = dctx.getDelegator();
String dataResourceId = (String) context.get("dataResourceId");
Locale locale = (Locale) context.get("locale");
try {
DataResourceWorker.clearAssociatedRenderCache(delegator, dataResourceId);
} catch (GeneralException e) {
Debug.logError(e, "Unable to clear associated render cache with dataResourceId=" + dataResourceId, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentClearAssociatedRenderCacheError", UtilMisc.toMap("dataResourceId", dataResourceId), locale));
}
return ServiceUtil.returnSuccess();
}
/**
* A top-level service for creating a DataResource and ElectronicText together.
*/
public static Map<String, Object> createDataResourceAndText(DispatchContext dctx, Map<String, ? extends Object> rcontext) {
Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
Map<String, Object> result = new HashMap<String, Object>();
Map<String, Object> thisResult = createDataResourceMethod(dctx, context);
if (thisResult.get(ModelService.RESPONSE_MESSAGE) != null) {
return ServiceUtil.returnError((String) thisResult.get(ModelService.ERROR_MESSAGE));
}
result.put("dataResourceId", thisResult.get("dataResourceId"));
context.put("dataResourceId", thisResult.get("dataResourceId"));
String dataResourceTypeId = (String) context.get("dataResourceTypeId");
if (dataResourceTypeId != null && dataResourceTypeId.equals("ELECTRONIC_TEXT")) {
thisResult = createElectronicText(dctx, context);
if (thisResult.get(ModelService.RESPONSE_MESSAGE) != null) {
return ServiceUtil.returnError((String) thisResult.get(ModelService.ERROR_MESSAGE));
}
}
return result;
}
/**
* A service wrapper for the createDataResourceMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> createDataResource(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = createDataResourceMethod(dctx, context);
return result;
}
public static Map<String, Object> createDataResourceMethod(DispatchContext dctx, Map<String, ? extends Object> rcontext) {
Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
Map<String, Object> result = new HashMap<String, Object>();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String userLoginId = (String) userLogin.get("userLoginId");
String createdByUserLogin = userLoginId;
String lastModifiedByUserLogin = userLoginId;
Timestamp createdDate = UtilDateTime.nowTimestamp();
Timestamp lastModifiedDate = UtilDateTime.nowTimestamp();
String dataTemplateTypeId = (String) context.get("dataTemplateTypeId");
if (UtilValidate.isEmpty(dataTemplateTypeId)) {
dataTemplateTypeId = "NONE";
context.put("dataTemplateTypeId", dataTemplateTypeId);
}
// If textData exists, then create DataResource and return dataResourceId
String dataResourceId = (String) context.get("dataResourceId");
if (UtilValidate.isEmpty(dataResourceId)) {
dataResourceId = delegator.getNextSeqId("DataResource");
}
if (Debug.infoOn()) {
Debug.logInfo("in createDataResourceMethod, dataResourceId:" + dataResourceId, module);
}
GenericValue dataResource = delegator.makeValue("DataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
dataResource.setNonPKFields(context);
dataResource.put("createdByUserLogin", createdByUserLogin);
dataResource.put("lastModifiedByUserLogin", lastModifiedByUserLogin);
dataResource.put("createdDate", createdDate);
dataResource.put("lastModifiedDate", lastModifiedDate);
// get first statusId for content out of the statusItem table if not provided
if (UtilValidate.isEmpty(dataResource.get("statusId"))) {
try {
GenericValue statusItem = EntityQuery.use(delegator).from("StatusItem").where("statusTypeId", "CONTENT_STATUS").orderBy("sequenceId").queryFirst();
if (statusItem != null) {
dataResource.put("statusId", statusItem.get("statusId"));
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
}
try {
dataResource.create();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
} catch (Exception e2) {
return ServiceUtil.returnError(e2.getMessage());
}
result.put("dataResourceId", dataResourceId);
result.put("dataResource", dataResource);
return result;
}
/**
* A service wrapper for the createElectronicTextMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> createElectronicText(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = createElectronicTextMethod(dctx, context);
return result;
}
public static Map<String, Object> createElectronicTextMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<String, Object>();
Delegator delegator = dctx.getDelegator();
String dataResourceId = (String) context.get("dataResourceId");
String textData = (String) context.get("textData");
if (UtilValidate.isNotEmpty(textData)) {
GenericValue electronicText = delegator.makeValue("ElectronicText", UtilMisc.toMap("dataResourceId", dataResourceId, "textData", textData));
try {
electronicText.create();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
}
return result;
}
/**
* A service wrapper for the createFileMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> createFile(DispatchContext dctx, Map<String, ? extends Object> context) {
return createFileMethod(dctx, context);
}
public static Map<String, Object> createFileNoPerm(DispatchContext dctx, Map<String, ? extends Object> rcontext) {
Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
context.put("skipPermissionCheck", "true");
return createFileMethod(dctx, context);
}
public static Map<String, Object> createFileMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
//GenericValue dataResource = (GenericValue) context.get("dataResource");
String dataResourceTypeId = (String) context.get("dataResourceTypeId");
String objectInfo = (String) context.get("objectInfo");
ByteBuffer binData = (ByteBuffer) context.get("binData");
String textData = (String) context.get("textData");
Locale locale = (Locale) context.get("locale");
// a few place holders
String prefix = "";
String sep = "";
// extended validation for binary/character data
if (UtilValidate.isNotEmpty(textData) && binData != null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentCannotProcessBothCharacterAndBinaryFile", locale));
}
// obtain a reference to the file
File file = null;
if (UtilValidate.isEmpty(objectInfo)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentUnableObtainReferenceToFile", UtilMisc.toMap("objectInfo", ""), locale));
}
if (UtilValidate.isEmpty(dataResourceTypeId) || dataResourceTypeId.equals("LOCAL_FILE") || dataResourceTypeId.equals("LOCAL_FILE_BIN")) {
file = new File(objectInfo);
if (!file.isAbsolute()) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentLocalFileDoesNotPointToAbsoluteLocation", locale));
}
} else if (dataResourceTypeId.equals("OFBIZ_FILE") || dataResourceTypeId.equals("OFBIZ_FILE_BIN")) {
prefix = System.getProperty("ofbiz.home");
if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
sep = "/";
}
file = new File(prefix + sep + objectInfo);
} else if (dataResourceTypeId.equals("CONTEXT_FILE") || dataResourceTypeId.equals("CONTEXT_FILE_BIN")) {
prefix = (String) context.get("rootDir");
if (UtilValidate.isEmpty(prefix)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentCannotFindContextFileWithEmptyContextRoot", locale));
}
if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
sep = "/";
}
file = new File(prefix + sep + objectInfo);
}
if (file == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentUnableObtainReferenceToFile", UtilMisc.toMap("objectInfo", objectInfo), locale));
}
// write the data to the file
if (UtilValidate.isNotEmpty(textData)) {
try {
FileWriter out = new FileWriter(file);
out.write(textData);
out.close();
} catch (IOException e) {
Debug.logWarning(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentUnableWriteCharacterDataToFile", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} else if (binData != null) {
try {
RandomAccessFile out = new RandomAccessFile(file, "rw");
out.write(binData.array());
out.close();
} catch (FileNotFoundException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentUnableToOpenFileForWriting", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
} catch (IOException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentUnableWriteBinaryDataToFile", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentNoContentFilePassed", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
Map<String, Object> result = ServiceUtil.returnSuccess();
return result;
}
/**
* A top-level service for updating a DataResource and ElectronicText together.
*/
public static Map<String, Object> updateDataResourceAndText(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> thisResult = updateDataResourceMethod(dctx, context);
if (thisResult.get(ModelService.RESPONSE_MESSAGE) != null) {
return ServiceUtil.returnError((String) thisResult.get(ModelService.ERROR_MESSAGE));
}
String dataResourceTypeId = (String) context.get("dataResourceTypeId");
if (dataResourceTypeId != null && dataResourceTypeId.equals("ELECTRONIC_TEXT")) {
thisResult = updateElectronicText(dctx, context);
if (thisResult.get(ModelService.RESPONSE_MESSAGE) != null) {
return ServiceUtil.returnError((String) thisResult.get(ModelService.ERROR_MESSAGE));
}
}
return ServiceUtil.returnSuccess();
}
/**
* A service wrapper for the updateDataResourceMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> updateDataResource(DispatchContext dctx, Map<String, ? extends Object> context) {
//context.put("skipPermissionCheck", null);
Map<String, Object> result = updateDataResourceMethod(dctx, context);
return result;
}
public static Map<String, Object> updateDataResourceMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<String, Object>();
Delegator delegator = dctx.getDelegator();
GenericValue dataResource = null;
Locale locale = (Locale) context.get("locale");
GenericValue userLogin = (GenericValue) context.get("userLogin");
String userLoginId = (String) userLogin.get("userLoginId");
String lastModifiedByUserLogin = userLoginId;
Timestamp lastModifiedDate = UtilDateTime.nowTimestamp();
// If textData exists, then create DataResource and return dataResourceId
String dataResourceId = (String) context.get("dataResourceId");
try {
dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentDataResourceNotFound", UtilMisc.toMap("parameters.dataResourceId", dataResourceId), locale));
}
dataResource.setNonPKFields(context);
dataResource.put("lastModifiedByUserLogin", lastModifiedByUserLogin);
dataResource.put("lastModifiedDate", lastModifiedDate);
try {
dataResource.store();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
result.put("dataResource", dataResource);
return result;
}
/**
* A service wrapper for the updateElectronicTextMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> updateElectronicText(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = updateElectronicTextMethod(dctx, context);
return result;
}
/**
* Because sometimes a DataResource will exist, but no ElectronicText has been created,
* this method will create an ElectronicText if it does not exist.
* @param dctx the dispatch context
* @param context the context
* @return update the ElectronicText
*/
public static Map<String, Object> updateElectronicTextMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<String, Object>();
Delegator delegator = dctx.getDelegator();
GenericValue electronicText = null;
Locale locale = (Locale) context.get("locale");
String dataResourceId = (String) context.get("dataResourceId");
result.put("dataResourceId", dataResourceId);
String contentId = (String) context.get("contentId");
result.put("contentId", contentId);
if (UtilValidate.isEmpty(dataResourceId)) {
Debug.logError("dataResourceId is null.", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentDataResourceIsNull", locale));
}
String textData = (String) context.get("textData");
if (Debug.verboseOn()) {
Debug.logVerbose("in updateElectronicText, textData:" + textData, module);
}
try {
electronicText = EntityQuery.use(delegator).from("ElectronicText").where("dataResourceId", dataResourceId).queryOne();
if (electronicText != null) {
electronicText.put("textData", textData);
electronicText.store();
} else {
electronicText = delegator.makeValue("ElectronicText");
electronicText.put("dataResourceId", dataResourceId);
electronicText.put("textData", textData);
electronicText.create();
}
} catch (GenericEntityException e) {
Debug.logWarning(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentElectronicTextNotFound", locale) + " " + e.getMessage());
}
return result;
}
/**
* A service wrapper for the updateFileMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> updateFile(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = null;
try {
result = updateFileMethod(dctx, context);
} catch (GenericServiceException e) {
return ServiceUtil.returnError(e.getMessage());
}
return result;
}
public static Map<String, Object> updateFileMethod(DispatchContext dctx, Map<String, ? extends Object> context) throws GenericServiceException {
Map<String, Object> result = new HashMap<String, Object>();
//GenericValue fileText = null;
Locale locale = (Locale) context.get("locale");
//String dataResourceId = (String) dataResource.get("dataResourceId");
String dataResourceTypeId = (String) context.get("dataResourceTypeId");
String objectInfo = (String) context.get("objectInfo");
String textData = (String) context.get("textData");
ByteBuffer binData = (ByteBuffer) context.get("binData");
String prefix = "";
File file = null;
String fileName = "";
String sep = "";
try {
if (UtilValidate.isEmpty(dataResourceTypeId) || dataResourceTypeId.startsWith("LOCAL_FILE")) {
fileName = prefix + sep + objectInfo;
file = new File(fileName);
if (!file.isAbsolute()) {
throw new GenericServiceException("File: " + fileName + " is not absolute.");
}
} else if (dataResourceTypeId.startsWith("OFBIZ_FILE")) {
prefix = System.getProperty("ofbiz.home");
if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
sep = "/";
}
file = new File(prefix + sep + objectInfo);
} else if (dataResourceTypeId.startsWith("CONTEXT_FILE")) {
prefix = (String) context.get("rootDir");
if (objectInfo.indexOf("/") != 0 && prefix.lastIndexOf("/") != (prefix.length() - 1)) {
sep = "/";
}
file = new File(prefix + sep + objectInfo);
}
if (file == null) {
throw new IOException("File: " + file + " is null");
}
// write the data to the file
if (UtilValidate.isNotEmpty(textData)) {
try {
FileWriter out = new FileWriter(file);
out.write(textData);
out.close();
} catch (IOException e) {
Debug.logWarning(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentUnableWriteCharacterDataToFile", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} else if (binData != null) {
try {
RandomAccessFile out = new RandomAccessFile(file, "rw");
out.setLength(binData.array().length);
out.write(binData.array());
out.close();
} catch (FileNotFoundException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentUnableToOpenFileForWriting", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
} catch (IOException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentUnableWriteBinaryDataToFile", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentNoContentFilePassed", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} catch (IOException e) {
Debug.logWarning(e, module);
throw new GenericServiceException(e.getMessage());
}
return result;
}
public static Map<String, Object> renderDataResourceAsText(DispatchContext dctx, Map<String, ? extends Object> context) throws GeneralException, IOException {
Map<String, Object> results = new HashMap<String, Object>();
Delegator delegator = dctx.getDelegator();
//LocalDispatcher dispatcher = dctx.getDispatcher();
Writer out = (Writer) context.get("outWriter");
Map<String, Object> templateContext = UtilGenerics.checkMap(context.get("templateContext"));
//GenericValue userLogin = (GenericValue) context.get("userLogin");
String dataResourceId = (String) context.get("dataResourceId");
if (templateContext != null && UtilValidate.isEmpty(dataResourceId)) {
dataResourceId = (String) templateContext.get("dataResourceId");
}
String mimeTypeId = (String) context.get("mimeTypeId");
if (templateContext != null && UtilValidate.isEmpty(mimeTypeId)) {
mimeTypeId = (String) templateContext.get("mimeTypeId");
}
Locale locale = (Locale) context.get("locale");
if (templateContext == null) {
templateContext = new HashMap<String, Object>();
}
// GenericValue view = (GenericValue) context.get("subContentDataResourceView");
Writer outWriter = new StringWriter();
DataResourceWorker.renderDataResourceAsText(delegator, dataResourceId, outWriter, templateContext, locale, mimeTypeId, true);
try {
out.write(outWriter.toString());
results.put("textData", outWriter.toString());
} catch (IOException e) {
Debug.logError(e, "Error rendering sub-content text", module);
return ServiceUtil.returnError(e.toString());
}
return results;
}
/**
* A service wrapper for the updateImageMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> updateImage(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = updateImageMethod(dctx, context);
return result;
}
public static Map<String, Object> updateImageMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<String, Object>();
Delegator delegator = dctx.getDelegator();
//Locale locale = (Locale) context.get("locale");
String dataResourceId = (String) context.get("dataResourceId");
ByteBuffer byteBuffer = (ByteBuffer)context.get("imageData");
if (byteBuffer != null) {
byte[] imageBytes = byteBuffer.array();
try {
GenericValue imageDataResource = EntityQuery.use(delegator).from("ImageDataResource").where("dataResourceId", dataResourceId).queryOne();
if (Debug.infoOn()) {
Debug.logInfo("imageDataResource(U):" + imageDataResource, module);
Debug.logInfo("imageBytes(U):" + imageBytes, module);
}
if (imageDataResource == null) {
return createImageMethod(dctx, context);
} else {
imageDataResource.setBytes("imageData", imageBytes);
imageDataResource.store();
}
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
}
return result;
}
/**
* A service wrapper for the createImageMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> createImage(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = createImageMethod(dctx, context);
return result;
}
public static Map<String, Object> createImageMethod(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = new HashMap<String, Object>();
Delegator delegator = dctx.getDelegator();
String dataResourceId = (String) context.get("dataResourceId");
ByteBuffer byteBuffer = (ByteBuffer)context.get("imageData");
if (byteBuffer != null) {
byte[] imageBytes = byteBuffer.array();
try {
GenericValue imageDataResource = delegator.makeValue("ImageDataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
//imageDataResource.set("imageData", imageBytes);
imageDataResource.setBytes("imageData", imageBytes);
if (Debug.infoOn()) {
Debug.logInfo("imageDataResource(C):" + imageDataResource, module);
}
imageDataResource.create();
} catch (GenericEntityException e) {
return ServiceUtil.returnError(e.getMessage());
}
}
return result;
}
/**
* A service wrapper for the createBinaryFileMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> createBinaryFile(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = null;
try {
result = createBinaryFileMethod(dctx, context);
} catch (GenericServiceException e) {
return ServiceUtil.returnError(e.getMessage());
}
return result;
}
public static Map<String, Object> createBinaryFileMethod(DispatchContext dctx, Map<String, ? extends Object> context) throws GenericServiceException {
Map<String, Object> result = new HashMap<String, Object>();
GenericValue dataResource = (GenericValue) context.get("dataResource");
//String dataResourceId = (String) dataResource.get("dataResourceId");
String dataResourceTypeId = (String) dataResource.get("dataResourceTypeId");
String objectInfo = (String) dataResource.get("objectInfo");
byte [] imageData = (byte []) context.get("imageData");
String rootDir = (String)context.get("rootDir");
File file = null;
if (Debug.infoOn()) {
Debug.logInfo("in createBinaryFileMethod, dataResourceTypeId:" + dataResourceTypeId, module);
Debug.logInfo("in createBinaryFileMethod, objectInfo:" + objectInfo, module);
Debug.logInfo("in createBinaryFileMethod, rootDir:" + rootDir, module);
}
try {
file = DataResourceWorker.getContentFile(dataResourceTypeId, objectInfo, rootDir);
} catch (FileNotFoundException e) {
Debug.logWarning(e, module);
throw new GenericServiceException(e.getMessage());
} catch (GeneralException e2) {
Debug.logWarning(e2, module);
throw new GenericServiceException(e2.getMessage());
}
if (Debug.infoOn()) {
Debug.logInfo("in createBinaryFileMethod, file:" + file, module);
Debug.logInfo("in createBinaryFileMethod, imageData:" + imageData.length, module);
}
if (imageData != null && imageData.length > 0) {
try {
FileOutputStream out = new FileOutputStream(file);
out.write(imageData);
if (Debug.infoOn()) {
Debug.logInfo("in createBinaryFileMethod, length:" + file.length(), module);
}
out.close();
} catch (IOException e) {
Debug.logWarning(e, module);
throw new GenericServiceException(e.getMessage());
}
}
return result;
}
/**
* A service wrapper for the createBinaryFileMethod method. Forces permissions to be checked.
*/
public static Map<String, Object> updateBinaryFile(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> result = null;
try {
result = updateBinaryFileMethod(dctx, context);
} catch (GenericServiceException e) {
return ServiceUtil.returnError(e.getMessage());
}
return result;
}
public static Map<String, Object> updateBinaryFileMethod(DispatchContext dctx, Map<String, ? extends Object> context) throws GenericServiceException {
Map<String, Object> result = new HashMap<String, Object>();
GenericValue dataResource = (GenericValue) context.get("dataResource");
//String dataResourceId = (String) dataResource.get("dataResourceId");
String dataResourceTypeId = (String) dataResource.get("dataResourceTypeId");
String objectInfo = (String) dataResource.get("objectInfo");
byte [] imageData = (byte []) context.get("imageData");
String rootDir = (String)context.get("rootDir");
File file = null;
if (Debug.infoOn()) {
Debug.logInfo("in updateBinaryFileMethod, dataResourceTypeId:" + dataResourceTypeId, module);
Debug.logInfo("in updateBinaryFileMethod, objectInfo:" + objectInfo, module);
Debug.logInfo("in updateBinaryFileMethod, rootDir:" + rootDir, module);
}
try {
file = DataResourceWorker.getContentFile(dataResourceTypeId, objectInfo, rootDir);
} catch (FileNotFoundException e) {
Debug.logWarning(e, module);
throw new GenericServiceException(e.getMessage());
} catch (GeneralException e2) {
Debug.logWarning(e2, module);
throw new GenericServiceException(e2.getMessage());
}
if (Debug.infoOn()) {
Debug.logInfo("in updateBinaryFileMethod, file:" + file, module);
Debug.logInfo("in updateBinaryFileMethod, imageData:" + imageData, module);
}
if (imageData != null && imageData.length > 0) {
try {
FileOutputStream out = new FileOutputStream(file);
out.write(imageData);
if (Debug.infoOn()) {
Debug.logInfo("in updateBinaryFileMethod, length:" + file.length(), module);
}
out.close();
} catch (IOException e) {
Debug.logWarning(e, module);
throw new GenericServiceException(e.getMessage());
}
}
return result;
}
}
@@ -0,0 +1,616 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.layout;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.content.ContentManagementWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericPK;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.minilang.MiniLangException;
import org.ofbiz.minilang.SimpleMapProcessor;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
/**
* LayoutEvents Class
*/
public class LayoutEvents {
public static final String module = LayoutEvents.class.getName();
public static final String err_resource = "ContentErrorUiLabels";
public static String createLayoutImage(HttpServletRequest request, HttpServletResponse response) {
Locale locale = UtilHttp.getLocale(request);
try {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
Map<String, Object> uploadResults = LayoutWorker.uploadImageAndParameters(request, "imageData");
//Debug.logVerbose("in createLayoutImage(java), uploadResults:" + uploadResults, "");
Map<String, Object> formInput = UtilGenerics.checkMap(uploadResults.get("formInput"));
Map<String, Object> context = new HashMap<String, Object>();
ByteBuffer byteWrap = (ByteBuffer) uploadResults.get("imageData");
if (byteWrap == null) {
String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.image_data_null", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
//Debug.logVerbose("in createLayoutImage, byteWrap(0):" + byteWrap, module);
String imageFileName = (String) uploadResults.get("imageFileName");
//Debug.logVerbose("in createLayoutImage(java), context:" + context, "");
String imageFileNameExt = null;
if (UtilValidate.isNotEmpty(imageFileName)) {
int pos = imageFileName.lastIndexOf(".");
if (pos >= 0) {
imageFileNameExt = imageFileName.substring(pos + 1);
}
}
String mimeTypeId = "image/" + imageFileNameExt;
List<Object> errorMessages = new LinkedList<Object>();
if (locale == null) {
locale = Locale.getDefault();
}
context.put("locale", locale);
try {
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentIn", formInput, context, errorMessages, locale);
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceIn", formInput, context, errorMessages, locale);
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocIn", formInput, context, errorMessages, locale);
} catch (MiniLangException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
context.put("dataResourceName", context.get("contentName"));
context.put("userLogin", session.getAttribute("userLogin"));
context.put("dataResourceTypeId", "IMAGE_OBJECT");
context.put("contentAssocTypeId", "SUB_CONTENT");
context.put("contentTypeId", "DOCUMENT");
context.put("contentIdTo", formInput.get("contentIdTo"));
context.put("textData", formInput.get("textData"));
String contentPurposeTypeId = (String) formInput.get("contentPurposeTypeId");
if (UtilValidate.isNotEmpty(contentPurposeTypeId)) {
context.put("contentPurposeList", UtilMisc.toList(contentPurposeTypeId));
}
Map<String, Object> result = dispatcher.runSync("persistContentAndAssoc", context);
//Debug.logVerbose("in createLayoutImage, result:" + result, module);
String dataResourceId = (String) result.get("dataResourceId");
String activeContentId = (String) result.get("contentId");
if (UtilValidate.isNotEmpty(activeContentId)) {
Map<String, Object> context2 = new HashMap<String, Object>();
context2.put("activeContentId", activeContentId);
//context2.put("dataResourceId", dataResourceId);
context2.put("contentAssocTypeId", result.get("contentAssocTypeId"));
context2.put("fromDate", result.get("fromDate"));
request.setAttribute("contentId", result.get("contentId"));
request.setAttribute("drDataResourceId", dataResourceId);
request.setAttribute("currentEntityName", "SubContentDataResourceId");
context2.put("contentIdTo", formInput.get("contentIdTo"));
context2.put("mapKey", formInput.get("mapKey"));
//Debug.logVerbose("in createLayoutImage, context2:" + context2, module);
dispatcher.runSync("deactivateAssocs", context2);
}
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
//Debug.logVerbose("in createLayoutImage, dataResource:" + dataResource, module);
// Use objectInfo field to store the name of the file, since there is no
// place in ImageDataResource for it.
if (dataResource != null) {
dataResource.set("objectInfo", imageFileName);
dataResource.set("mimeTypeId", mimeTypeId);
dataResource.store();
}
// See if this needs to be a create or an update procedure
GenericValue imageDataResource = EntityQuery.use(delegator).from("ImageDataResource").where("dataResourceId", dataResourceId).queryOne();
//Debug.logVerbose("in createLayoutImage, imageDataResource(0):" + imageDataResource, module);
if (imageDataResource == null) {
imageDataResource = delegator.makeValue("ImageDataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
imageDataResource.set("imageData", byteWrap.array());
imageDataResource.create();
} else {
imageDataResource.set("imageData", byteWrap.array());
imageDataResource.store();
}
} catch (GenericEntityException e3) {
request.setAttribute("_ERROR_MESSAGE_", e3.getMessage());
return "error";
} catch (GenericServiceException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
return "success";
}
public static String updateLayoutImage(HttpServletRequest request, HttpServletResponse response) {
Locale locale = UtilHttp.getLocale(request);
try {
Delegator delegator = (Delegator) request.getAttribute("delegator");
HttpSession session = request.getSession();
Map<String, Object> uploadResults = LayoutWorker.uploadImageAndParameters(request, "imageData");
Map<String, Object> context = UtilGenerics.checkMap(uploadResults.get("formInput"));
ByteBuffer byteWrap = (ByteBuffer) uploadResults.get("imageData");
if (byteWrap == null) {
String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.image_data_null", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
String imageFileName = (String) uploadResults.get("imageFileName");
Debug.logVerbose("in createLayoutImage(java), context:" + context, "");
context.put("userLogin", session.getAttribute("userLogin"));
context.put("dataResourceTypeId", "IMAGE_OBJECT");
context.put("contentAssocTypeId", "SUB_CONTENT");
context.put("contentTypeId", "DOCUMENT");
context.put("mimeType", context.get("drMimeType"));
context.put("drMimeType", null);
context.put("objectInfo", context.get("drobjectInfo"));
context.put("drObjectInfo", null);
context.put("drDataResourceTypeId", null);
String dataResourceId = (String) context.get("drDataResourceId");
Debug.logVerbose("in createLayoutImage(java), dataResourceId:" + dataResourceId, "");
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
Debug.logVerbose("in createLayoutImage(java), dataResource:" + dataResource, "");
// Use objectInfo field to store the name of the file, since there is no
// place in ImageDataResource for it.
Debug.logVerbose("in createLayoutImage(java), imageFileName:" + imageFileName, "");
if (dataResource != null) {
//dataResource.set("objectInfo", imageFileName);
dataResource.setNonPKFields(context);
dataResource.store();
}
// See if this needs to be a create or an update procedure
GenericValue imageDataResource = EntityQuery.use(delegator).from("ImageDataResource").where("dataResourceId", dataResourceId).queryOne();
if (imageDataResource == null) {
imageDataResource = delegator.makeValue("ImageDataResource", UtilMisc.toMap("dataResourceId", dataResourceId));
imageDataResource.set("imageData", byteWrap.array());
imageDataResource.create();
} else {
imageDataResource.set("imageData", byteWrap.array());
imageDataResource.store();
}
} catch (GenericEntityException e3) {
request.setAttribute("_ERROR_MESSAGE_", e3.getMessage());
return "error";
}
return "success";
}
public static String replaceSubContent(HttpServletRequest request, HttpServletResponse response) {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
Locale locale = UtilHttp.getLocale(request);
Map<String, Object> context = new HashMap<String, Object>();
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
Debug.logVerbose("in replaceSubContent, paramMap:" + paramMap, module);
String dataResourceId = (String) paramMap.get("dataResourceId");
if (UtilValidate.isEmpty(dataResourceId)) {
String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.data_ressource_id_null", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
String contentIdTo = (String) paramMap.get("contentIdTo");
if (UtilValidate.isEmpty(contentIdTo)) {
String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.content_id_to_null", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
String mapKey = (String) paramMap.get("mapKey");
context.put("dataResourceId", dataResourceId);
String contentId = (String) paramMap.get("contentId");
context.put("userLogin", session.getAttribute("userLogin"));
/*
// If contentId is missing
if (UtilValidate.isEmpty(contentId)) {
// Look for an existing associated Content
try {
GenericValue dataResourceContentView = EntityQuery.use(delegator).from("DataResourceContentView")
.where("dataResourceId", dataResourceId)
.queryFirst();
if (dataResourceContentView != null) {
contentId = dataResourceContentView.getString("coContentId");
}
} catch (GenericEntityException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
// Else, create and associate a Content
}
*/
if (UtilValidate.isNotEmpty(contentId)) {
context.put("contentId", contentId);
context.put("contentIdTo", contentIdTo);
context.put("mapKey", mapKey);
context.put("contentAssocTypeId", "SUB_CONTENT");
try {
Map<String, Object> result = dispatcher.runSync("persistContentAndAssoc", context);
//Debug.logVerbose("in replaceSubContent, result:" + result, module);
request.setAttribute("contentId", contentIdTo);
Map<String, Object> context2 = new HashMap<String, Object>();
context2.put("activeContentId", contentId);
//context2.put("dataResourceId", dataResourceId);
context2.put("contentAssocTypeId", "SUB_CONTENT");
context2.put("fromDate", result.get("fromDate"));
request.setAttribute("drDataResourceId", null);
request.setAttribute("currentEntityName", "ContentDataResourceView");
context2.put("contentIdTo", contentIdTo);
context2.put("mapKey", mapKey);
//Debug.logVerbose("in replaceSubContent, context2:" + context2, module);
dispatcher.runSync("deactivateAssocs", context2);
} catch (GenericServiceException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
}
return "success";
}
public static String cloneLayout(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
Locale locale = UtilHttp.getLocale(request);
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String contentId = (String) paramMap.get("contentId");
Debug.logVerbose("in cloneLayout, contentId:" + contentId, "");
if (UtilValidate.isEmpty(contentId)) {
String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.content_id_empty", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
String contentIdTo = (String) paramMap.get("contentIdTo");
Debug.logVerbose("in cloneLayout, contentIdTo:" + contentIdTo, "");
GenericValue content = null;
GenericValue newContent = null;
GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
String userLoginId = (String) userLogin.get("userLoginId");
List<GenericValue> entityList = null;
String newId = null;
String newDataResourceId = null;
try {
content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
Debug.logVerbose("in cloneLayout, content:" + content, "");
if (content == null) {
String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.content_empty", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
newContent = delegator.makeValue("Content", content);
Debug.logVerbose("in cloneLayout, newContent:" + newContent, "");
String oldName = (String) content.get("contentName");
newId = delegator.getNextSeqId("Content");
newContent.set("contentId", newId);
String dataResourceId = (String) content.get("dataResourceId");
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).queryOne();
if (dataResource != null) {
GenericValue newDataResource = delegator.makeValue("DataResource", dataResource);
Debug.logVerbose("in cloneLayout, newDataResource:" + newDataResource, "");
String dataResourceName = "Copy:" + (String) dataResource.get("dataResourceName");
newDataResource.set("dataResourceName", dataResourceName);
newDataResourceId = delegator.getNextSeqId("DataResource");
newDataResource.set("dataResourceId", newDataResourceId);
newDataResource.set("createdDate", UtilDateTime.nowTimestamp());
newDataResource.set("lastModifiedDate", UtilDateTime.nowTimestamp());
newDataResource.set("createdByUserLogin", userLoginId);
newDataResource.set("lastModifiedByUserLogin", userLoginId);
newDataResource.create();
}
newContent.set("contentName", "Copy - " + oldName);
newContent.set("createdDate", UtilDateTime.nowTimestamp());
newContent.set("lastModifiedDate", UtilDateTime.nowTimestamp());
newContent.set("createdByUserLogin", userLoginId);
newContent.set("lastModifiedByUserLogin", userLoginId);
newContent.create();
Debug.logVerbose("in cloneLayout, newContent:" + newContent, "");
GenericValue newContentAssoc = delegator.makeValue("ContentAssoc");
newContentAssoc.set("contentId", newId);
newContentAssoc.set("contentIdTo", "TEMPLATE_MASTER");
newContentAssoc.set("contentAssocTypeId", "SUB_CONTENT");
newContentAssoc.set("fromDate", UtilDateTime.nowTimestamp());
newContentAssoc.create();
Debug.logVerbose("in cloneLayout, newContentAssoc:" + newContentAssoc, "");
} catch (GenericEntityException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
Map<String, Object> serviceIn = new HashMap<String, Object>();
Map<String, Object> results = null;
serviceIn.put("fromDate", UtilDateTime.nowTimestamp());
serviceIn.put("contentId", contentId);
serviceIn.put("userLogin", session.getAttribute("userLogin"));
serviceIn.put("direction", "From");
serviceIn.put("thruDate", null);
serviceIn.put("assocTypes", UtilMisc.toList("SUB_CONTENT"));
try {
results = dispatcher.runSync("getAssocAndContentAndDataResource", serviceIn);
entityList = UtilGenerics.checkList(results.get("entityList"));
if (UtilValidate.isEmpty(entityList)) {
String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.no_subcontent", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
}
} catch (GenericServiceException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
serviceIn = new HashMap<String, Object>();
serviceIn.put("userLogin", session.getAttribute("userLogin"));
// Can't count on records being unique
Map<String, GenericValue> beenThere = new HashMap<String, GenericValue>();
for (int i=0; i<entityList.size(); i++) {
GenericValue view = entityList.get(i);
List<Object> errorMessages = new LinkedList<Object>();
if (locale == null) {
locale = Locale.getDefault();
}
try {
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocIn", view, serviceIn, errorMessages, locale);
} catch (IllegalArgumentException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
} catch (MiniLangException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
String contentIdFrom = (String) view.get("contentId");
String mapKey = (String) view.get("caMapKey");
Timestamp fromDate = (Timestamp) view.get("caFromDate");
Timestamp thruDate = (Timestamp) view.get("caThruDate");
Debug.logVerbose("in cloneLayout, contentIdFrom:" + contentIdFrom + " fromDate:" + fromDate + " thruDate:" + thruDate + " mapKey:" + mapKey, "");
if (beenThere.get(contentIdFrom) == null) {
serviceIn.put("contentIdFrom", contentIdFrom);
serviceIn.put("contentIdTo", newId);
serviceIn.put("fromDate", UtilDateTime.nowTimestamp());
serviceIn.put("thruDate", null);
try {
results = dispatcher.runSync("persistContentAndAssoc", serviceIn);
} catch (GenericServiceException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
beenThere.put(contentIdFrom, view);
}
}
GenericValue view = delegator.makeValue("ContentDataResourceView");
view.set("contentId", newId);
view.set("drDataResourceId", newDataResourceId);
Debug.logVerbose("in cloneLayout, view:" + view, "");
ContentManagementWorker.setCurrentEntityMap(request, view);
request.setAttribute("contentId", view.get("contentId"));
request.setAttribute("drDataResourceId", view.get("drDataResourceId"));
return "success";
}
public static String createLayoutSubContent(HttpServletRequest request, HttpServletResponse response) {
try {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String contentIdTo = (String) paramMap.get("contentIdTo");
String mapKey = (String) paramMap.get("mapKey");
if (Debug.verboseOn()) {
Debug.logVerbose("in createSubContent, contentIdTo:" + contentIdTo, module);
Debug.logVerbose("in createSubContent, mapKey:" + mapKey, module);
}
Map<String, Object> context = new HashMap<String, Object>();
List<Object> errorMessages = null;
Locale loc = (Locale) request.getSession().getServletContext().getAttribute("locale");
if (loc == null) {
loc = Locale.getDefault();
}
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
context.put("userLogin", userLogin);
String rootDir = request.getSession().getServletContext().getRealPath("/");
context.put("rootDir", rootDir);
try {
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentIn", paramMap, context, errorMessages, loc);
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceIn", paramMap, context, errorMessages, loc);
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocIn", paramMap, context, errorMessages, loc);
} catch (MiniLangException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
context.put("dataResourceName", context.get("contentName"));
String contentPurposeTypeId = (String) paramMap.get("contentPurposeTypeId");
if (UtilValidate.isNotEmpty(contentPurposeTypeId)) {
context.put("contentPurposeList", UtilMisc.toList(contentPurposeTypeId));
}
context.put("contentIdTo", paramMap.get("contentIdTo"));
context.put("mapKey", paramMap.get("mapKey"));
context.put("textData", paramMap.get("textData"));
context.put("contentAssocTypeId", "SUB_CONTENT");
if (Debug.verboseOn()) {
Debug.logVerbose("in createSubContent, context:" + context, module);
}
Map<String, Object> result = dispatcher.runSync("persistContentAndAssoc", context);
boolean isError = ModelService.RESPOND_ERROR.equals(result.get(ModelService.RESPONSE_MESSAGE));
if (isError) {
request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));
return "error";
}
if (Debug.verboseOn()) {
Debug.logVerbose("in createLayoutFile, result:" + result, module);
}
String contentId = (String) result.get("contentId");
String dataResourceId = (String) result.get("dataResourceId");
request.setAttribute("contentId", contentId);
request.setAttribute("drDataResourceId", dataResourceId);
request.setAttribute("currentEntityName", "SubContentDataResourceId");
Map<String, Object> context2 = new HashMap<String, Object>();
context2.put("activeContentId", contentId);
//context2.put("dataResourceId", dataResourceId);
context2.put("contentAssocTypeId", "SUB_CONTENT");
context2.put("fromDate", result.get("fromDate"));
context2.put("contentIdTo", contentIdTo);
context2.put("mapKey", mapKey);
context2.put("userLogin", userLogin);
//Debug.logVerbose("in replaceSubContent, context2:" + context2, module);
dispatcher.runSync("deactivateAssocs", context2);
} catch (GenericServiceException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
return "success";
}
public static String updateLayoutSubContent(HttpServletRequest request, HttpServletResponse response) {
try {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
// String contentIdTo = (String) paramMap.get("contentIdTo");
// String mapKey = (String) paramMap.get("mapKey");
Map<String, Object> context = new HashMap<String, Object>();
List<Object> errorMessages = null;
Locale loc = (Locale) request.getSession().getServletContext().getAttribute("locale");
if (loc == null) {
loc = Locale.getDefault();
}
context.put("locale", loc);
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
context.put("userLogin", userLogin);
String rootDir = request.getSession().getServletContext().getRealPath("/");
context.put("rootDir", rootDir);
try {
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentIn", paramMap, context, errorMessages, loc);
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceIn", paramMap, context, errorMessages, loc);
SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocIn", paramMap, context, errorMessages, loc);
} catch (MiniLangException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
context.put("dataResourceName", context.get("contentName"));
String contentPurposeTypeId = (String) paramMap.get("contentPurposeTypeId");
if (UtilValidate.isNotEmpty(contentPurposeTypeId)) {
context.put("contentPurposeList", UtilMisc.toList(contentPurposeTypeId));
}
context.put("contentIdTo", paramMap.get("contentIdTo"));
context.put("textData", paramMap.get("textData"));
context.put("contentAssocTypeId", null);
Map<String, Object> result = dispatcher.runSync("persistContentAndAssoc", context);
boolean isError = ModelService.RESPOND_ERROR.equals(result.get(ModelService.RESPONSE_MESSAGE));
if (isError) {
request.setAttribute("_ERROR_MESSAGE_", result.get(ModelService.ERROR_MESSAGE));
return "error";
}
String contentId = (String) result.get("contentId");
String dataResourceId = (String) result.get("dataResourceId");
request.setAttribute("contentId", contentId);
request.setAttribute("drDataResourceId", dataResourceId);
request.setAttribute("currentEntityName", "SubContentDataResourceId");
/*
Map context2 = new HashMap<String, Object>();
context2.put("activeContentId", contentId);
//context2.put("dataResourceId", dataResourceId);
context2.put("contentAssocTypeId", "SUB_CONTENT");
context2.put("fromDate", result.get("fromDate"));
context2.put("contentIdTo", contentIdTo);
context2.put("mapKey", mapKey);
//Debug.logVerbose("in replaceSubContent, context2:" + context2, module);
Map result2 = dispatcher.runSync("deactivateAssocs", context2);
*/
} catch (GenericServiceException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
return "success";
}
public static String copyToClip(HttpServletRequest request, HttpServletResponse response) {
Delegator delegator = (Delegator) request.getAttribute("delegator");
Map<String, Object> paramMap = UtilHttp.getParameterMap(request);
String entityName = (String) paramMap.get("entityName");
Locale locale = UtilHttp.getLocale(request);
if (UtilValidate.isEmpty(entityName)) {
String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.entityname_empty", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
GenericValue v = delegator.makeValue(entityName);
GenericPK passedPK = v.getPrimaryKey();
Collection<String> keyColl = passedPK.getAllKeys();
for (String attrName : keyColl) {
String attrVal = (String)request.getAttribute(attrName);
if (attrVal == null) {
attrVal = (String) paramMap.get(attrName);
}
Debug.logVerbose("in copyToClip, attrName:" + attrName,"");
Debug.logVerbose("in copyToClip, attrVal:" + attrVal,"");
if (UtilValidate.isNotEmpty(attrVal)) {
passedPK.put(attrName,attrVal);
} else {
String errMsg = UtilProperties.getMessage(LayoutEvents.err_resource, "layoutEvents.empty", locale);
request.setAttribute("_ERROR_MESSAGE_", attrName + " " + errMsg);
return "error";
}
}
ContentManagementWorker.mruAdd(request, passedPK);
return "success";
}
}
@@ -0,0 +1,121 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.layout;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.service.ServiceUtil;
/**
* LayoutWorker Class
*/
public final class LayoutWorker {
public static final String module = LayoutWorker.class.getName();
private static final String err_resource = "ContentErrorUiLabels";
private LayoutWorker() {}
/**
* Uploads image data from a form and stores it in ImageDataResource.
* Expects key data in a field identitified by the "idField" value
* and the binary data to be in a field id'd by uploadField.
*/
public static Map<String, Object> uploadImageAndParameters(HttpServletRequest request, String uploadField) {
//Debug.logVerbose("in uploadAndStoreImage", "");
Locale locale = UtilHttp.getLocale(request);
Map<String, Object> results = new HashMap<String, Object>();
Map<String, String> formInput = new HashMap<String, String>();
results.put("formInput", formInput);
ServletFileUpload fu = new ServletFileUpload(new DiskFileItemFactory(10240, new File(new File("runtime"), "tmp")));
List<FileItem> lst = null;
try {
lst = UtilGenerics.checkList(fu.parseRequest(request));
} catch (FileUploadException e4) {
return ServiceUtil.returnError(e4.getMessage());
}
if (lst.size() == 0) {
String errMsg = UtilProperties.getMessage(err_resource,
"layoutEvents.no_files_uploaded", locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
//Debug.logWarning("[DataEvents.uploadImage] No files uploaded", module);
return ServiceUtil.returnError(UtilProperties.getMessage(err_resource,
"layoutEvents.no_files_uploaded", locale));
}
// This code finds the idField and the upload FileItems
FileItem fi = null;
FileItem imageFi = null;
for (int i=0; i < lst.size(); i++) {
fi = lst.get(i);
String fieldName = fi.getFieldName();
String fieldStr = fi.getString();
if (fi.isFormField()) {
formInput.put(fieldName, fieldStr);
request.setAttribute(fieldName, fieldStr);
//Debug.logVerbose("in uploadAndStoreImage, fieldName:" + fieldName + " fieldStr:" + fieldStr, "");
}
if (fieldName.equals(uploadField)) {
imageFi = fi;
//MimeType of upload file
results.put("uploadMimeType", fi.getContentType());
}
}
if (imageFi == null) {
String errMsg = UtilProperties.getMessage(err_resource,
"layoutEvents.image_null", UtilMisc.toMap("imageFi", imageFi), locale);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
//Debug.logWarning("[DataEvents.uploadImage] imageFi(" + imageFi + ") is null", module);
return null;
}
byte[] imageBytes = imageFi.get();
ByteBuffer byteWrap = ByteBuffer.wrap(imageBytes);
results.put("imageData", byteWrap);
results.put("imageFileName", imageFi.getName());
//Debug.logVerbose("in uploadAndStoreImage, results:" + results, "");
return results;
}
public static ByteBuffer returnByteBuffer(Map<String, ByteBuffer> map) {
ByteBuffer byteBuff = map.get("imageData");
return byteBuff;
}
}
@@ -0,0 +1,98 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.openoffice;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import com.sun.star.io.XSeekable;
import com.sun.star.io.XInputStream;
import com.sun.star.io.BufferSizeExceededException;
import com.sun.star.io.NotConnectedException;
/**
* OpenOfficeByteArrayInputStream Class
*/
public class OpenOfficeByteArrayInputStream extends ByteArrayInputStream implements XInputStream, XSeekable {
public static final String module = OpenOfficeByteArrayInputStream.class.getName();
public OpenOfficeByteArrayInputStream(byte [] bytes) {
super(bytes);
}
public long getPosition() throws com.sun.star.io.IOException {
return this.pos;
}
public long getLength() throws com.sun.star.io.IOException {
return this.count;
}
public void seek(long pos1) throws com.sun.star.io.IOException, IllegalArgumentException {
this.pos = (int)pos1;
}
public void skipBytes(int pos1) throws BufferSizeExceededException,
NotConnectedException, com.sun.star.io.IOException {
skip(pos1);
}
public void closeInput() throws NotConnectedException, com.sun.star.io.IOException {
try {
close();
} catch (IOException e) {
String errMsg = e.getMessage();
throw new com.sun.star.io.IOException(errMsg, this);
}
}
public int readBytes(byte [][]buf, int pos2) throws BufferSizeExceededException, NotConnectedException, com.sun.star.io.IOException {
int bytesRead = 0;
byte [] buf2 = new byte[pos2];
try {
bytesRead = super.read(buf2);
} catch (IOException e) {
String errMsg = e.getMessage();
throw new com.sun.star.io.IOException(errMsg, this);
}
if (bytesRead > 0) {
if (bytesRead < pos2) {
byte [] buf3 = new byte[bytesRead];
System.arraycopy(buf2, 0, buf3, 0, bytesRead);
buf[0] = buf3;
} else {
buf[0] = buf2;
}
} else {
buf[0] = new byte[0];
}
return bytesRead;
}
public int readSomeBytes(byte [][]buf, int pos2) throws BufferSizeExceededException, NotConnectedException, com.sun.star.io.IOException {
return readBytes(buf, pos2);
}
}
@@ -0,0 +1,75 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.openoffice;
import java.io.ByteArrayOutputStream;
import com.sun.star.io.XSeekable;
import com.sun.star.io.XOutputStream;
import com.sun.star.io.BufferSizeExceededException;
import com.sun.star.io.NotConnectedException;
/**
* OpenOfficeByteArrayOutputStream Class
*/
public class OpenOfficeByteArrayOutputStream extends ByteArrayOutputStream implements XOutputStream {
public static final String module = OpenOfficeByteArrayOutputStream.class.getName();
public OpenOfficeByteArrayOutputStream() {
super();
// TODO Auto-generated constructor stub
}
public OpenOfficeByteArrayOutputStream(int arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public void writeBytes(byte[] buf) throws BufferSizeExceededException, NotConnectedException, com.sun.star.io.IOException
{
try {
write(buf);
} catch (java.io.IOException e) {
throw(new com.sun.star.io.IOException(e.getMessage()));
}
}
public void closeOutput() throws BufferSizeExceededException, NotConnectedException, com.sun.star.io.IOException
{
try {
super.flush();
close();
} catch (java.io.IOException e) {
throw(new com.sun.star.io.IOException(e.getMessage()));
}
}
public void flush()
{
try {
super.flush();
} catch (java.io.IOException e) {
}
}
}
@@ -0,0 +1,374 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.openoffice;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.util.Map;
import java.util.Random;
import java.sql.Timestamp;
import java.lang.Math;
import java.net.MalformedURLException;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.util.EntityUtilProperties;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XDesktop;
import com.sun.star.frame.XDispatchHelper;
import com.sun.star.frame.XDispatchProvider;
import com.sun.star.frame.XFrame;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
/**
* OpenOfficeServices Class
*/
public class OpenOfficeServices {
public static final String module = OpenOfficeServices.class.getName();
/**
* Use OpenOffice to convert documents between types
* This service requires that the "content.temp.dir" directory be set in the content.properties file.
* This value should be operating system dependent with "\\" separators for Windows
* and "/" for Linux/Unix.
*/
public static Map<String, Object> convertDocumentByteBuffer(DispatchContext dctx, Map<String, ? extends Object> context) {
Map results = ServiceUtil.returnSuccess();
Delegator delegator = dctx.getDelegator();
XMultiComponentFactory xmulticomponentfactory = null;
//String uniqueSeqNum = delegator.getNextSeqId("OOTempDir");
Timestamp ts = UtilDateTime.nowTimestamp();
Random random = new Random(ts.getTime());
String uniqueSeqNum = Integer.toString(Math.abs(random.nextInt()));
String fileInName = "OOIN_" + uniqueSeqNum;
String fileOutName = "OOOUT_" + uniqueSeqNum;
File fileIn = null;
File fileOut = null;
ByteBuffer inByteBuffer = (ByteBuffer) context.get("inByteBuffer");
String inputMimeType = (String) context.get("inputMimeType");
String outputMimeType = (String) context.get("outputMimeType");
String extName = OpenOfficeWorker.getExtensionFromMimeType(outputMimeType);
fileOutName += "." + extName;
// if these are empty don't worry, the OpenOfficeWorker down below will take care of it
String oooHost = (String) context.get("oooHost");
String oooPort = (String) context.get("oooPort");
try {
xmulticomponentfactory = OpenOfficeWorker.getRemoteServer(oooHost, oooPort);
byte[] inByteArray = inByteBuffer.array();
// The following line work in linux, but not Windows or Mac environment. It is preferred because it does not use temporary files
//OpenOfficeByteArrayInputStream oobais = new OpenOfficeByteArrayInputStream(inByteArray);
//Debug.logInfo("Doing convertDocumentByteBuffer, inBytes size is [" + inByteArray.length + "]", module);
//OpenOfficeByteArrayOutputStream baos = OpenOfficeWorker.convertOODocByteStreamToByteStream(xmulticomponentfactory, oobais, inputMimeType, outputMimeType);
String tempDir = EntityUtilProperties.getPropertyValue("content", "content.temp.dir", delegator);
fileIn = new File(tempDir + fileInName);
FileOutputStream fos = new FileOutputStream(fileIn);
fos.write(inByteArray);
fos.close();
Debug.logInfo("fileIn:" + tempDir + fileInName, module);
OpenOfficeWorker.convertOODocToFile(xmulticomponentfactory, tempDir + fileInName, tempDir + fileOutName, outputMimeType);
fileOut = new File(tempDir + fileOutName);
FileInputStream fis = new FileInputStream(fileOut);
int c;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((c=fis.read()) > -1) {
baos.write(c);
}
fis.close();
results.put("outByteBuffer", ByteBuffer.wrap(baos.toByteArray()));
baos.close();
} catch (MalformedURLException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.toString());
} catch (FileNotFoundException e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
} catch (IOException e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
} catch (Exception e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
} finally {
if (fileIn != null) fileIn.delete();
if (fileOut != null) fileOut.delete();
}
return results;
}
/**
* Use OpenOffice to convert documents between types
*/
public static Map<String, Object> convertDocument(DispatchContext dctx, Map<String, ? extends Object> context) {
XMultiComponentFactory xmulticomponentfactory = null;
String stringUrl = "file:///" + context.get("filenameFrom");
String stringConvertedFile = "file:///" + context.get("filenameTo");
String filterName = "file:///" + context.get("filterName");
// if these are empty don't worry, the OpenOfficeWorker down below will take care of it
String oooHost = (String) context.get("oooHost");
String oooPort = (String) context.get("oooPort");
try {
xmulticomponentfactory = OpenOfficeWorker.getRemoteServer(oooHost, oooPort);
OpenOfficeWorker.convertOODocToFile(xmulticomponentfactory, stringUrl, stringConvertedFile, filterName);
Map results = ServiceUtil.returnSuccess();
return results;
} catch (IOException e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
} catch (Exception e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
}
}
/**
* Use OpenOffice to convert documents between types
*/
public static Map<String, Object> convertDocumentFileToFile(DispatchContext dctx, Map<String, ? extends Object> context) {
XMultiComponentFactory xmulticomponentfactory = null;
String stringUrl = (String) context.get("filenameFrom");
String stringConvertedFile = (String) context.get("filenameTo");
String inputMimeType = (String) context.get("inputMimeType");
String outputMimeType = (String) context.get("outputMimeType");
// if these are empty don't worry, the OpenOfficeWorker down below will take care of it
String oooHost = (String) context.get("oooHost");
String oooPort = (String) context.get("oooPort");
try {
xmulticomponentfactory = OpenOfficeWorker.getRemoteServer(oooHost, oooPort);
File inputFile = new File(stringUrl);
long fileSize = inputFile.length();
FileInputStream fis = new FileInputStream(inputFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream((int)fileSize);
int c;
while ((c = fis.read()) != -1) {
baos.write(c);
}
OpenOfficeByteArrayInputStream oobais = new OpenOfficeByteArrayInputStream(baos.toByteArray());
OpenOfficeByteArrayOutputStream oobaos = OpenOfficeWorker.convertOODocByteStreamToByteStream(xmulticomponentfactory, oobais, inputMimeType, outputMimeType);
FileOutputStream fos = new FileOutputStream(stringConvertedFile);
fos.write(oobaos.toByteArray());
fos.close();
fis.close();
oobais.close();
oobaos.close();
Map results = ServiceUtil.returnSuccess();
return results;
} catch (IOException e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
} catch (Exception e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
}
}
/**
* Use OpenOffice to convert documents between types
*/
public static Map<String, Object> convertDocumentStreamToStream(DispatchContext dctx, Map<String, ? extends Object> context) {
XMultiComponentFactory xmulticomponentfactory = null;
String stringUrl = "file:///" + context.get("filenameFrom");
String stringConvertedFile = "file:///" + context.get("filenameTo");
String inputMimeType = (String) context.get("inputMimeType");
String outputMimeType = (String) context.get("outputMimeType");
// if these are empty don't worry, the OpenOfficeWorker down below will take care of it
String oooHost = (String) context.get("oooHost");
String oooPort = (String) context.get("oooPort");
try {
xmulticomponentfactory = OpenOfficeWorker.getRemoteServer(oooHost, oooPort);
File inputFile = new File(stringUrl);
long fileSize = inputFile.length();
FileInputStream fis = new FileInputStream(inputFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream((int)fileSize);
int c;
while ((c = fis.read()) != -1) {
baos.write(c);
}
OpenOfficeByteArrayInputStream oobais = new OpenOfficeByteArrayInputStream(baos.toByteArray());
OpenOfficeByteArrayOutputStream oobaos = OpenOfficeWorker.convertOODocByteStreamToByteStream(xmulticomponentfactory, oobais, inputMimeType, outputMimeType);
FileOutputStream fos = new FileOutputStream(stringConvertedFile);
fos.write(oobaos.toByteArray());
fos.close();
fis.close();
oobais.close();
oobaos.close();
Map results = ServiceUtil.returnSuccess();
return results;
} catch (IOException e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
} catch (Exception e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
}
}
/**
* Use OpenOffice to compare documents
*/
public static Map<String, Object> compareDocuments(DispatchContext dctx, Map<String, ? extends Object> context) {
XMultiComponentFactory xmulticomponentfactory = null;
String stringUrl = "file:///" + context.get("filenameFrom");
String stringOriginalFile = "file:///" + context.get("filenameOriginal");
String stringOutFile = "file:///" + context.get("filenameOut");
// if these are empty don't worry, the OpenOfficeWorker down below will take care of it
String oooHost = (String)context.get("oooHost");
String oooPort = (String)context.get("oooPort");
try {
xmulticomponentfactory = OpenOfficeWorker.getRemoteServer(oooHost, oooPort);
} catch (IOException e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
} catch (Exception e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(e.toString());
}
//System.out.println("xmulticomponentfactory: " + xmulticomponentfactory);
// Converting the document to the favoured type
try {
// Composing the URL
// Query for the XPropertySet interface.
XPropertySet xpropertysetMultiComponentFactory = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xmulticomponentfactory);
// Get the default context from the office server.
Object objectDefaultContext = xpropertysetMultiComponentFactory.getPropertyValue("DefaultContext");
// Query for the interface XComponentContext.
XComponentContext xcomponentcontext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, objectDefaultContext);
/* A desktop environment contains tasks with one or more
frames in which components can be loaded. Desktop is the
environment for components which can instanciate within
frames. */
Object desktopObj = xmulticomponentfactory.createInstanceWithContext("com.sun.star.frame.Desktop", xcomponentcontext);
XDesktop desktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktopObj);
XComponentLoader xcomponentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, desktopObj);
// Preparing properties for loading the document
PropertyValue propertyvalue[] = new PropertyValue[ 1 ];
// Setting the flag for hidding the open document
propertyvalue[ 0 ] = new PropertyValue();
propertyvalue[ 0 ].Name = "Hidden";
propertyvalue[ 0 ].Value = Boolean.valueOf(true);
//TODO: Hardcoding opening word documents -- this will need to change.
//propertyvalue[ 1 ] = new PropertyValue();
//propertyvalue[ 1 ].Name = "FilterName";
//propertyvalue[ 1 ].Value = "HTML (StarWriter)";
// Loading the wanted document
Object objectDocumentToStore = xcomponentloader.loadComponentFromURL(stringUrl, "_blank", 0, propertyvalue);
// Getting an object that will offer a simple way to store a document to a URL.
XStorable xstorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, objectDocumentToStore);
// Preparing properties for comparing the document
propertyvalue = new PropertyValue[ 1 ];
// Setting the flag for overwriting
propertyvalue[ 0 ] = new PropertyValue();
propertyvalue[ 0 ].Name = "URL";
propertyvalue[ 0 ].Value = stringOriginalFile;
// Setting the filter name
//propertyvalue[ 1 ] = new PropertyValue();
//propertyvalue[ 1 ].Name = "FilterName";
//propertyvalue[ 1 ].Value = context.get("convertFilterName");
XFrame frame = desktop.getCurrentFrame();
//XFrame frame = (XFrame) UnoRuntime.queryInterface(XFrame.class, desktop);
Object dispatchHelperObj = xmulticomponentfactory.createInstanceWithContext("com.sun.star.frame.DispatchHelper", xcomponentcontext);
XDispatchHelper dispatchHelper = (XDispatchHelper) UnoRuntime.queryInterface(XDispatchHelper.class, dispatchHelperObj);
XDispatchProvider dispatchProvider = (XDispatchProvider) UnoRuntime.queryInterface(XDispatchProvider.class, frame);
dispatchHelper.executeDispatch(dispatchProvider, ".uno:CompareDocuments", "", 0, propertyvalue);
// Preparing properties for storing the document
propertyvalue = new PropertyValue[ 1 ];
// Setting the flag for overwriting
propertyvalue[ 0 ] = new PropertyValue();
propertyvalue[ 0 ].Name = "Overwrite";
propertyvalue[ 0 ].Value = Boolean.valueOf(true);
// Setting the filter name
//propertyvalue[ 1 ] = new PropertyValue();
//propertyvalue[ 1 ].Name = "FilterName";
//propertyvalue[ 1 ].Value = context.get("convertFilterName");
Debug.logInfo("stringOutFile: "+stringOutFile, module);
// Storing and converting the document
xstorable.storeToURL(stringOutFile, propertyvalue);
// Getting the method dispose() for closing the document
XComponent xcomponent = (XComponent) UnoRuntime.queryInterface(XComponent.class,
xstorable);
// Closing the converted document
xcomponent.dispose();
Map results = ServiceUtil.returnSuccess();
return results;
} catch (Exception e) {
Debug.logError(e, "Error in OpenOffice operation: ", module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource,
"ContentConvertingDocumentError",
UtilMisc.toMap("errorString", e.toString()), locale));
}
}
}
@@ -0,0 +1,360 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.openoffice;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import com.sun.star.beans.PropertyValue;
import com.sun.star.beans.XPropertySet;
import com.sun.star.bridge.XUnoUrlResolver;
import com.sun.star.container.XNameAccess;
import com.sun.star.frame.XComponentLoader;
import com.sun.star.frame.XStorable;
import com.sun.star.lang.XComponent;
import com.sun.star.lang.XMultiComponentFactory;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.uno.XComponentContext;
import com.sun.star.uri.ExternalUriReferenceTranslator;
/**
* OpenOfficeWorker Class
*
* Note that for this to work you must start OpenOffice with a command such as the following:
* <code>soffice -accept=socket,host=localhost,port=8100;urp;</code>
*/
public final class OpenOfficeWorker{
public static final String module = OpenOfficeWorker.class.getName();
private OpenOfficeWorker() {}
/**
* Use OpenOffice to convert documents between types
*/
public static XMultiComponentFactory getRemoteServer(String host, String port) throws IOException, Exception {
if (UtilValidate.isEmpty(host)) host = UtilProperties.getPropertyValue("openoffice-uno", "oo.host", "localhost");
if (UtilValidate.isEmpty(port)) port = UtilProperties.getPropertyValue("openoffice-uno", "oo.port", "8100");
XMultiComponentFactory xmulticomponentfactory = null;
XComponentContext xcomponentcontext = null;
Object objectUrlResolver = null;
XUnoUrlResolver xurlresolver = null;
Object objectInitial = null;
// Converting the document to the favoured type
try {
/* Bootstraps a component context with the jurt base components
registered. Component context to be granted to a component for running.
Arbitrary values can be retrieved from the context. */
xcomponentcontext = com.sun.star.comp.helper.Bootstrap.createInitialComponentContext(null);
/* Gets the service manager instance to be used (or null). This method has
been added for convenience, because the service manager is a often used
object. */
xmulticomponentfactory = xcomponentcontext.getServiceManager();
/* Creates an instance of the component UnoUrlResolver which
supports the services specified by the factory. */
objectUrlResolver = xmulticomponentfactory.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", xcomponentcontext);
// Create a new url resolver
xurlresolver = (XUnoUrlResolver) UnoRuntime.queryInterface(XUnoUrlResolver.class, objectUrlResolver);
// Resolves an object that is specified as follow:
// uno:<connection description>;<protocol description>;<initial object name>
String url = "uno:socket,host=" + host + ",port=" + port + ";urp;StarOffice.ServiceManager";
objectInitial = xurlresolver.resolve(url);
// Create a service manager from the initial object
xmulticomponentfactory = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class, objectInitial);
} catch (Exception e) {
// TODO: None of this works. Need a programmable start solution.
//String ooxvfb = UtilProperties.getPropertyValue("openoffice-uno", "oo.start.xvfb");
//String ooexport = UtilProperties.getPropertyValue("openoffice-uno", "oo.start.export");
// String oosoffice = UtilProperties.getPropertyValue("openoffice-uno", "oo.start.soffice");
//Process procXvfb = Runtime.getRuntime().exec(ooxvfb);
//Process procExport = Runtime.getRuntime().exec(ooexport);
/*
Process procSoffice = Runtime.getRuntime().exec(oosoffice);
Thread.sleep(3000);
objectInitial = xurlresolver.resolve("uno:socket,host=" + host + ",port=" + port + ";urp;StarOffice.ServiceManager");
xmulticomponentfactory = (XMultiComponentFactory) UnoRuntime.queryInterface(XMultiComponentFactory.class, objectInitial);
Debug.logInfo("soffice started. " + procSoffice, module);
*/
String errMsg = "Error connecting to OpenOffice with host [" + host + "] and port [" + port + "]: " + e.toString();
Debug.logError(e, errMsg, module);
throw new IllegalArgumentException(errMsg);
}
return xmulticomponentfactory;
}
public static String listFilterNamesEvent(HttpServletRequest request, HttpServletResponse response) {
XMultiComponentFactory factory = null;
try {
factory = getRemoteServer("localhost", "8100");
List filterList = getFilterNames(factory);
request.setAttribute("filterList", filterList);
} catch (IOException e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
} catch (Exception e) {
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
return "error";
}
return "success";
}
public static List getFilterNames(XMultiComponentFactory xmulticomponentfactory) throws Exception {
XPropertySet xPropertySet = (XPropertySet)UnoRuntime.queryInterface(XPropertySet.class, xmulticomponentfactory);
Object oDefaultContext = xPropertySet.getPropertyValue("DefaultContext");
XComponentContext xComponentContext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, oDefaultContext);
Object filterFactory = xmulticomponentfactory.createInstanceWithContext("com.sun.star.document.FilterFactory", xComponentContext);
XNameAccess xNameAccess = (XNameAccess)UnoRuntime.queryInterface(XNameAccess.class, filterFactory);
String [] filterNames = xNameAccess.getElementNames();
//String [] serviceNames = filterFactory.getAvailableServiceNames();
for (int i=0; i < filterNames.length; i++) {
String s = filterNames[i];
Debug.logInfo(s, module);
/*
if (s.toLowerCase().indexOf("filter") >= 0) {
Debug.logInfo("FILTER: " + s, module);
}
if (s.toLowerCase().indexOf("desktop") >= 0) {
Debug.logInfo("DESKTOP: " + s, module);
}
*/
}
List filterNameList = UtilMisc.toListArray(filterNames);
return filterNameList;
}
public static void convertOODocToFile(XMultiComponentFactory xmulticomponentfactory, String fileInPath, String fileOutPath, String outputMimeType) throws FileNotFoundException, IOException, MalformedURLException, Exception {
// Converting the document to the favoured type
// Query for the XPropertySet interface.
XPropertySet xpropertysetMultiComponentFactory = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xmulticomponentfactory);
// Get the default context from the office server.
Object objectDefaultContext = xpropertysetMultiComponentFactory.getPropertyValue("DefaultContext");
// Query for the interface XComponentContext.
XComponentContext xcomponentcontext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, objectDefaultContext);
/* A desktop environment contains tasks with one or more
frames in which components can be loaded. Desktop is the
environment for components which can instanciate within
frames. */
Object desktopObj = xmulticomponentfactory.createInstanceWithContext("com.sun.star.frame.Desktop", xcomponentcontext);
//XDesktop desktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktopObj);
XComponentLoader xcomponentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, desktopObj);
// Preparing properties for loading the document
PropertyValue propertyvalue[] = new PropertyValue[ 2 ];
// Setting the flag for hidding the open document
propertyvalue[ 0 ] = new PropertyValue();
propertyvalue[ 0 ].Name = "Hidden";
propertyvalue[ 0 ].Value = Boolean.valueOf(false);
propertyvalue[ 1 ] = new PropertyValue();
propertyvalue[ 1 ].Name = "UpdateDocMode";
propertyvalue[ 1 ].Value = "1";
// Loading the wanted document
String stringUrl = convertToUrl(fileInPath, xcomponentcontext);
Debug.logInfo("stringUrl:" + stringUrl, module);
Object objectDocumentToStore = xcomponentloader.loadComponentFromURL(stringUrl, "_blank", 0, propertyvalue);
// Getting an object that will offer a simple way to store a document to a URL.
XStorable xstorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, objectDocumentToStore);
// Preparing properties for converting the document
propertyvalue = new PropertyValue[ 3 ];
// Setting the flag for overwriting
propertyvalue[ 0 ] = new PropertyValue();
propertyvalue[ 0 ].Name = "Overwrite";
propertyvalue[ 0 ].Value = Boolean.valueOf(true);
// Setting the filter name
// Preparing properties for converting the document
String filterName = getFilterNameFromMimeType(outputMimeType);
propertyvalue[ 1 ] = new PropertyValue();
propertyvalue[ 1 ].Name = "FilterName";
propertyvalue[ 1 ].Value = filterName;
propertyvalue[2] = new PropertyValue();
propertyvalue[2].Name = "CompressionMode";
propertyvalue[2].Value = "1";
// Storing and converting the document
//File newFile = new File(stringConvertedFile);
//newFile.createNewFile();
String stringConvertedFile = convertToUrl(fileOutPath, xcomponentcontext);
Debug.logInfo("stringConvertedFile: "+stringConvertedFile, module);
xstorable.storeToURL(stringConvertedFile, propertyvalue);
// Getting the method dispose() for closing the document
XComponent xcomponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xstorable);
// Closing the converted document
xcomponent.dispose();
return;
}
public static OpenOfficeByteArrayOutputStream convertOODocByteStreamToByteStream(XMultiComponentFactory xmulticomponentfactory,
OpenOfficeByteArrayInputStream is, String inputMimeType, String outputMimeType) throws Exception {
// Query for the XPropertySet interface.
XPropertySet xpropertysetMultiComponentFactory = (XPropertySet) UnoRuntime.queryInterface(XPropertySet.class, xmulticomponentfactory);
// Get the default context from the office server.
Object objectDefaultContext = xpropertysetMultiComponentFactory.getPropertyValue("DefaultContext");
// Query for the interface XComponentContext.
XComponentContext xcomponentcontext = (XComponentContext) UnoRuntime.queryInterface(XComponentContext.class, objectDefaultContext);
/* A desktop environment contains tasks with one or more
frames in which components can be loaded. Desktop is the
environment for components which can instanciate within
frames. */
Object desktopObj = xmulticomponentfactory.createInstanceWithContext("com.sun.star.frame.Desktop", xcomponentcontext);
//XDesktop desktop = (XDesktop) UnoRuntime.queryInterface(XDesktop.class, desktopObj);
XComponentLoader xcomponentloader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, desktopObj);
// Preparing properties for loading the document
PropertyValue propertyvalue[] = new PropertyValue[2];
// Setting the flag for hidding the open document
propertyvalue[0] = new PropertyValue();
propertyvalue[0].Name = "Hidden";
propertyvalue[0].Value = Boolean.TRUE;
//
propertyvalue[1] = new PropertyValue();
propertyvalue[1].Name = "InputStream";
propertyvalue[1].Value = is;
// Loading the wanted document
Object objectDocumentToStore = xcomponentloader.loadComponentFromURL("private:stream", "_blank", 0, propertyvalue);
if (objectDocumentToStore == null) {
Debug.logError("Could not get objectDocumentToStore object from xcomponentloader.loadComponentFromURL", module);
}
// Getting an object that will offer a simple way to store a document to a URL.
XStorable xstorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, objectDocumentToStore);
if (xstorable == null) {
Debug.logError("Could not get XStorable object from UnoRuntime.queryInterface", module);
}
// Preparing properties for converting the document
String filterName = getFilterNameFromMimeType(outputMimeType);
propertyvalue = new PropertyValue[4];
propertyvalue[0] = new PropertyValue();
propertyvalue[0].Name = "OutputStream";
OpenOfficeByteArrayOutputStream os = new OpenOfficeByteArrayOutputStream();
propertyvalue[0].Value = os;
// Setting the filter name
propertyvalue[1] = new PropertyValue();
propertyvalue[1].Name = "FilterName";
propertyvalue[1].Value = filterName;
// Setting the flag for overwriting
propertyvalue[3] = new PropertyValue();
propertyvalue[3].Name = "Overwrite";
propertyvalue[3].Value = Boolean.TRUE;
// For PDFs
propertyvalue[2] = new PropertyValue();
propertyvalue[2].Name = "CompressionMode";
propertyvalue[2].Value = "1";
xstorable.storeToURL("private:stream", propertyvalue);
//xstorable.storeToURL("file:///home/byersa/testdoc1_file.pdf", propertyvalue);
// Getting the method dispose() for closing the document
XComponent xcomponent = (XComponent) UnoRuntime.queryInterface(XComponent.class, xstorable);
// Closing the converted document
xcomponent.dispose();
return os;
}
public static String getFilterNameFromMimeType(String mimeType) {
String filterName = "";
if (UtilValidate.isEmpty(mimeType)) {
filterName = "HTML";
} else if (mimeType.equalsIgnoreCase("application/pdf")) {
filterName = "writer_pdf_Export";
} else if (mimeType.equalsIgnoreCase("application/msword")) {
filterName = "MS Word 97";
} else if (mimeType.equalsIgnoreCase("text/html")) {
filterName = "HTML (StarWriter)";
} else {
filterName = "HTML";
}
return filterName;
}
public static String getExtensionFromMimeType(String mimeType) {
String extension = "";
if (UtilValidate.isEmpty(mimeType)) {
extension = "html";
} else if (mimeType.equalsIgnoreCase("application/pdf")) {
extension = "pdf";
} else if (mimeType.equalsIgnoreCase("application/msword")) {
extension = "doc";
} else if (mimeType.equalsIgnoreCase("text/html")) {
extension = "html";
} else {
extension = "html";
}
return extension;
}
public static String convertToUrl(String filePath, XComponentContext xComponentContext) throws MalformedURLException {
String returnUrl = null;
File f = new File(filePath);
URL u = f.toURL();
returnUrl = ExternalUriReferenceTranslator.create(xComponentContext).translateToInternal(u.toExternalForm());
return returnUrl;
}
}
@@ -0,0 +1,263 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.output;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttribute;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.PrintRequestAttribute;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterName;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.MimeConstants;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.collections.MapStack;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.util.EntityUtilProperties;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.webapp.view.ApacheFopWorker;
import org.ofbiz.widget.renderer.ScreenRenderer;
import org.ofbiz.widget.renderer.ScreenStringRenderer;
import org.ofbiz.widget.renderer.fo.FoFormRenderer;
import org.ofbiz.widget.renderer.macro.MacroScreenRenderer;
/**
* Output Services
*/
public class OutputServices {
public final static String module = OutputServices.class.getName();
protected static final FoFormRenderer foFormRenderer = new FoFormRenderer();
public static final String resource = "ContentUiLabels";
public static Map<String, Object> sendPrintFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
Locale locale = (Locale) serviceContext.get("locale");
String screenLocation = (String) serviceContext.remove("screenLocation");
Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
String contentType = (String) serviceContext.remove("contentType");
String printerContentType = (String) serviceContext.remove("printerContentType");
if (UtilValidate.isEmpty(screenContext)) {
screenContext = new HashMap<String, Object>();
}
screenContext.put("locale", locale);
if (UtilValidate.isEmpty(contentType)) {
contentType = "application/postscript";
}
if (UtilValidate.isEmpty(printerContentType)) {
printerContentType = contentType;
}
try {
MapStack<String> screenContextTmp = MapStack.create();
screenContextTmp.put("locale", locale);
Writer writer = new StringWriter();
// substitute the freemarker variables...
ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(EntityUtilProperties.getPropertyValue("widget", "screenfop.name", dctx.getDelegator()),
EntityUtilProperties.getPropertyValue("widget", "screenfop.screenrenderer", dctx.getDelegator()));
ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenStringRenderer);
screensAtt.populateContextForService(dctx, screenContext);
screenContextTmp.putAll(screenContext);
screensAtt.getContext().put("formStringRenderer", foFormRenderer);
screensAtt.render(screenLocation);
// create the input stream for the generation
StreamSource src = new StreamSource(new StringReader(writer.toString()));
// create the output stream for the generation
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
ApacheFopWorker.transform(src, null, fop);
baos.flush();
baos.close();
// Print is sent
DocFlavor psInFormat = new DocFlavor.INPUT_STREAM(printerContentType);
InputStream bais = new ByteArrayInputStream(baos.toByteArray());
DocAttributeSet docAttributeSet = new HashDocAttributeSet();
List<Object> docAttributes = UtilGenerics.checkList(serviceContext.remove("docAttributes"));
if (UtilValidate.isNotEmpty(docAttributes)) {
for (Object da : docAttributes) {
Debug.logInfo("Adding DocAttribute: " + da, module);
docAttributeSet.add((DocAttribute) da);
}
}
Doc myDoc = new SimpleDoc(bais, psInFormat, docAttributeSet);
PrintService printer = null;
// lookup the print service for the supplied printer name
String printerName = (String) serviceContext.remove("printerName");
if (UtilValidate.isNotEmpty(printerName)) {
PrintServiceAttributeSet printServiceAttributes = new HashPrintServiceAttributeSet();
printServiceAttributes.add(new PrinterName(printerName, locale));
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributes);
if (printServices.length > 0) {
printer = printServices[0];
Debug.logInfo("Using printer: " + printer.getName(), module);
if (!printer.isDocFlavorSupported(psInFormat)) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotSupportDocFlavorFormat", UtilMisc.toMap("psInFormat", psInFormat, "printerName", printer.getName()), locale));
}
}
if (printer == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotFound", UtilMisc.toMap("printerName", printerName), locale));
}
} else {
// if no printer name was supplied, try to get the default printer
printer = PrintServiceLookup.lookupDefaultPrintService();
if (printer != null) {
Debug.logInfo("No printer name supplied, using default printer: " + printer.getName(), module);
}
}
if (printer == null) {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPrinterNotAvailable", locale));
}
PrintRequestAttributeSet praset = new HashPrintRequestAttributeSet();
List<Object> printRequestAttributes = UtilGenerics.checkList(serviceContext.remove("printRequestAttributes"));
if (UtilValidate.isNotEmpty(printRequestAttributes)) {
for (Object pra : printRequestAttributes) {
Debug.logInfo("Adding PrintRequestAttribute: " + pra, module);
praset.add((PrintRequestAttribute) pra);
}
}
DocPrintJob job = printer.createPrintJob();
job.print(myDoc, praset);
} catch (Exception e) {
Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
}
return ServiceUtil.returnSuccess();
}
public static Map<String, Object> createFileFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) {
Locale locale = (Locale) serviceContext.get("locale");
Delegator delegator = dctx.getDelegator();
String screenLocation = (String) serviceContext.remove("screenLocation");
Map<String, Object> screenContext = UtilGenerics.checkMap(serviceContext.remove("screenContext"));
String contentType = (String) serviceContext.remove("contentType");
String filePath = (String) serviceContext.remove("filePath");
String fileName = (String) serviceContext.remove("fileName");
if (UtilValidate.isEmpty(screenContext)) {
screenContext = new HashMap<String, Object>();
}
screenContext.put("locale", locale);
if (UtilValidate.isEmpty(contentType)) {
contentType = "application/pdf";
}
try {
MapStack<String> screenContextTmp = MapStack.create();
screenContextTmp.put("locale", locale);
Writer writer = new StringWriter();
// substitute the freemarker variables...
ScreenStringRenderer foScreenStringRenderer = new MacroScreenRenderer(EntityUtilProperties.getPropertyValue("widget", "screenfop.name", dctx.getDelegator()),
EntityUtilProperties.getPropertyValue("widget", "screenfop.screenrenderer", dctx.getDelegator()));
ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenStringRenderer);
screensAtt.populateContextForService(dctx, screenContext);
screenContextTmp.putAll(screenContext);
screensAtt.getContext().put("formStringRenderer", foFormRenderer);
screensAtt.render(screenLocation);
// create the input stream for the generation
StreamSource src = new StreamSource(new StringReader(writer.toString()));
// create the output stream for the generation
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Fop fop = ApacheFopWorker.createFopInstance(baos, MimeConstants.MIME_PDF);
ApacheFopWorker.transform(src, null, fop);
baos.flush();
baos.close();
fileName += UtilDateTime.nowAsString();
if ("application/pdf".equals(contentType)) {
fileName += ".pdf";
} else if ("application/postscript".equals(contentType)) {
fileName += ".ps";
} else if ("text/plain".equals(contentType)) {
fileName += ".txt";
}
if (UtilValidate.isEmpty(filePath)) {
filePath = EntityUtilProperties.getPropertyValue("content", "content.output.path", "/output", delegator);
}
File file = new File(filePath, fileName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(baos.toByteArray());
fos.close();
} catch (Exception e) {
Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale));
}
return ServiceUtil.returnSuccess();
}
}
@@ -0,0 +1,85 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.report;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
import org.ofbiz.base.util.Debug;
import org.ofbiz.entity.GenericEntity;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.util.EntityListIterator;
/**
* <code>JREntityListIteratorDataSource</code>
*/
public class JREntityListIteratorDataSource implements JRDataSource {
public static final String module = JREntityListIteratorDataSource.class.getName();
private EntityListIterator entityListIterator = null;
private GenericEntity currentEntity = null;
public JREntityListIteratorDataSource(EntityListIterator entityListIterator) {
this.entityListIterator = entityListIterator;
}
public boolean next() throws JRException {
if (this.entityListIterator == null) {
return false;
}
Object nextObj = this.entityListIterator.next();
if (nextObj != null) {
if (nextObj instanceof GenericEntity) {
this.currentEntity = (GenericEntity) nextObj;
} else {
throw new JRException("Current collection object does not seem to be a GenericEntity (or GenericValue or GenericPK).");
}
return true;
} else {
// nothing left, close here...
try {
this.entityListIterator.close();
} catch (GenericEntityException e) {
Debug.logError(e, "Error closing EntityListIterator in Jasper Reports DataSource", module);
throw new JRException(e);
}
this.entityListIterator = null;
return false;
}
}
public Object getFieldValue(JRField jrField) throws JRException {
Object value = null;
if (this.currentEntity != null) {
try {
value = this.currentEntity.get(jrField.getName());
} catch (IllegalArgumentException e) {
try {
value = this.currentEntity.get(org.ofbiz.entity.model.ModelUtil.dbNameToVarName(jrField.getName()));
} catch (IllegalArgumentException ex) {
throw new JRException("The specified field name [" + jrField.getName() + "] is not a valid field-name for the entity: " + this.currentEntity.getEntityName(), e);
}
}
}
return value;
}
}
@@ -0,0 +1,75 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.report;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;
/**
* <code>JRMapCollectionDataSource</code>
*/
public class JRMapCollectionDataSource implements JRDataSource {
private Collection data = null;
private Iterator iterator = null;
private Map currentMap = null;
public JRMapCollectionDataSource(Collection mapCollection) {
this.data = mapCollection;
if (data != null) {
this.iterator = data.iterator();
}
}
public boolean next() throws JRException {
boolean hasNext = false;
if (this.iterator != null) {
hasNext = this.iterator.hasNext();
if (hasNext) {
try {
this.currentMap = (Map) this.iterator.next();
} catch (Exception e) {
throw new JRException("Current collection object does not seem to be a Map.", e);
}
}
}
return hasNext;
}
public Object getFieldValue(JRField jrField) throws JRException {
Object value = null;
if (currentMap != null) {
value = currentMap.get(jrField.getName());
}
return value;
}
}
@@ -0,0 +1,637 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.survey;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.content.data.DataResourceWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ModelService;
import org.ofbiz.service.ServiceUtil;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.PdfDictionary;
import com.lowagie.text.pdf.PdfName;
import com.lowagie.text.pdf.PdfObject;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;
/**
* PdfSurveyServices Class
*/
public class PdfSurveyServices {
public static final String module = PdfSurveyServices.class.getName();
public static final String resource = "ContentUiLabels";
/**
*
*/
public static Map<String, Object> buildSurveyFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
GenericValue userLogin = (GenericValue) context.get("userLogin");
Locale locale = (Locale) context.get("locale");
Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
String surveyId = null;
try {
String surveyName = (String) context.get("surveyName");
ByteArrayOutputStream os = new ByteArrayOutputStream();
ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
PdfReader pdfReader = new PdfReader(byteBuffer.array());
PdfStamper pdfStamper = new PdfStamper(pdfReader, os);
AcroFields acroFields = pdfStamper.getAcroFields();
Map<String, Object> acroFieldMap = UtilGenerics.checkMap(acroFields.getFields());
String contentId = (String) context.get("contentId");
GenericValue survey = null;
surveyId = (String) context.get("surveyId");
if (UtilValidate.isEmpty(surveyId)) {
survey = delegator.makeValue("Survey", UtilMisc.toMap("surveyName", surveyName));
survey.set("surveyId", surveyId);
survey.set("allowMultiple", "Y");
survey.set("allowUpdate", "Y");
survey = delegator.createSetNextSeqId(survey);
surveyId = survey.getString("surveyId");
}
// create a SurveyQuestionCategory to put the questions in
Map<String, Object> createCategoryResultMap = dispatcher.runSync("createSurveyQuestionCategory", UtilMisc.<String, Object>toMap("description", "From AcroForm in Content [" + contentId + "] for Survey [" + surveyId + "]", "userLogin", userLogin));
String surveyQuestionCategoryId = (String) createCategoryResultMap.get("surveyQuestionCategoryId");
pdfStamper.setFormFlattening(true);
for (String fieldName : acroFieldMap.keySet()) {
AcroFields.Item item = acroFields.getFieldItem(fieldName);
int type = acroFields.getFieldType(fieldName);
String value = acroFields.getField(fieldName);
Debug.logInfo("fieldName:" + fieldName + "; item: " + item + "; value: " + value, module);
GenericValue surveyQuestion = delegator.makeValue("SurveyQuestion", UtilMisc.toMap("question", fieldName));
String surveyQuestionId = delegator.getNextSeqId("SurveyQuestion");
surveyQuestion.set("surveyQuestionId", surveyQuestionId);
surveyQuestion.set("surveyQuestionCategoryId", surveyQuestionCategoryId);
if (type == AcroFields.FIELD_TYPE_TEXT) {
surveyQuestion.set("surveyQuestionTypeId", "TEXT_SHORT");
} else if (type == AcroFields.FIELD_TYPE_RADIOBUTTON) {
surveyQuestion.set("surveyQuestionTypeId", "OPTION");
} else if (type == AcroFields.FIELD_TYPE_LIST || type == AcroFields.FIELD_TYPE_COMBO) {
surveyQuestion.set("surveyQuestionTypeId", "OPTION");
// TODO: handle these specially with the acroFields.getListOptionDisplay (and getListOptionExport?)
/*String[] listOptionDisplayArray = acroFields.getListOptionDisplay(fieldName);
String[] listOptionExportArray = acroFields.getListOptionExport(fieldName);
Debug.logInfo("listOptionDisplayArray: " + listOptionDisplayArray + "; listOptionExportArray: " + listOptionExportArray, module);*/
} else {
surveyQuestion.set("surveyQuestionTypeId", "TEXT_SHORT");
Debug.logWarning("Building Survey from PDF, fieldName=[" + fieldName + "]: don't know how to handle field type: " + type + "; defaulting to short text", module);
}
// ==== create a good sequenceNum based on tab order or if no tab order then the page location
Integer tabPage = item.getPage(0);
Integer tabOrder = item.getTabOrder(0);
Debug.logInfo("tabPage=" + tabPage + ", tabOrder=" + tabOrder, module);
//array of float multiple of 5. For each of this groups the values are: [page, llx, lly, urx, ury]
float[] fieldPositions = acroFields.getFieldPositions(fieldName);
float fieldPage = fieldPositions[0];
float fieldLlx = fieldPositions[1];
float fieldLly = fieldPositions[2];
float fieldUrx = fieldPositions[3];
float fieldUry = fieldPositions[4];
Debug.logInfo("fieldPage=" + fieldPage + ", fieldLlx=" + fieldLlx + ", fieldLly=" + fieldLly + ", fieldUrx=" + fieldUrx + ", fieldUry=" + fieldUry, module);
Long sequenceNum = null;
if (tabPage != null && tabOrder != null) {
sequenceNum = Long.valueOf(tabPage.intValue() * 1000 + tabOrder.intValue());
Debug.logInfo("tabPage=" + tabPage + ", tabOrder=" + tabOrder + ", sequenceNum=" + sequenceNum, module);
} else if (fieldPositions.length > 0) {
sequenceNum = Long.valueOf((long) fieldPage * 10000 + (long) fieldLly * 1000 + (long) fieldLlx);
Debug.logInfo("fieldPage=" + fieldPage + ", fieldLlx=" + fieldLlx + ", fieldLly=" + fieldLly + ", fieldUrx=" + fieldUrx + ", fieldUry=" + fieldUry + ", sequenceNum=" + sequenceNum, module);
}
// TODO: need to find something better to put into these fields...
String annotation = null;
for (int k = 0; k < item.size(); ++k) {
PdfDictionary dict = item.getWidget(k);
// if the "/Type" value is "/Annot", then get the value of "/TU" for the annotation
/* Interesting... this doesn't work, I guess we have to iterate to find the stuff...
PdfObject typeValue = dict.get(new PdfName("/Type"));
if (typeValue != null && "/Annot".equals(typeValue.toString())) {
PdfObject tuValue = dict.get(new PdfName("/TU"));
annotation = tuValue.toString();
}
*/
PdfObject typeValue = null;
PdfObject tuValue = null;
Set<PdfName> dictKeys = UtilGenerics.checkSet(dict.getKeys());
for (PdfName dictKeyName : dictKeys) {
PdfObject dictObject = dict.get(dictKeyName);
if ("/Type".equals(dictKeyName.toString())) {
typeValue = dictObject;
} else if ("/TU".equals(dictKeyName.toString())) {
tuValue = dictObject;
}
//Debug.logInfo("AcroForm widget fieldName[" + fieldName + "] dictKey[" + dictKeyName.toString() + "] dictValue[" + dictObject.toString() + "]", module);
}
if (tuValue != null && typeValue != null && "/Annot".equals(typeValue.toString())) {
annotation = tuValue.toString();
}
}
surveyQuestion.set("description", fieldName);
if (UtilValidate.isNotEmpty(annotation)) {
surveyQuestion.set("question", annotation);
} else {
surveyQuestion.set("question", fieldName);
}
GenericValue surveyQuestionAppl = delegator.makeValue("SurveyQuestionAppl", UtilMisc.toMap("surveyId", surveyId, "surveyQuestionId", surveyQuestionId));
surveyQuestionAppl.set("fromDate", nowTimestamp);
surveyQuestionAppl.set("externalFieldRef", fieldName);
if (sequenceNum != null) {
surveyQuestionAppl.set("sequenceNum", sequenceNum);
}
surveyQuestion.create();
surveyQuestionAppl.create();
}
pdfStamper.close();
if (UtilValidate.isNotEmpty(contentId)) {
survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
survey.set("acroFormContentId", contentId);
survey.store();
}
} catch (GenericEntityException e) {
Debug.logError(e, "Error generating PDF: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale));
} catch (GeneralException e) {
Debug.logError(e, "Error generating PDF: " + e.getMessage(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.getMessage()), locale));
} catch (Exception e) {
Debug.logError(e, "Error generating PDF: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale));
}
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("surveyId", surveyId);
return results;
}
/**
*
*/
public static Map<String, Object> buildSurveyResponseFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
String surveyResponseId = null;
Locale locale = (Locale) context.get("locale");
try {
Delegator delegator = dctx.getDelegator();
String partyId = (String)context.get("partyId");
String surveyId = (String)context.get("surveyId");
//String contentId = (String)context.get("contentId");
surveyResponseId = (String)context.get("surveyResponseId");
if (UtilValidate.isNotEmpty(surveyResponseId)) {
GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
if (surveyResponse != null) {
surveyId = surveyResponse.getString("surveyId");
}
} else {
surveyResponseId = delegator.getNextSeqId("SurveyResponse");
GenericValue surveyResponse = delegator.makeValue("SurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId, "surveyId", surveyId, "partyId", partyId));
surveyResponse.set("responseDate", UtilDateTime.nowTimestamp());
surveyResponse.set("lastModifiedDate", UtilDateTime.nowTimestamp());
surveyResponse.create();
}
ByteArrayOutputStream os = new ByteArrayOutputStream();
ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
PdfReader r = new PdfReader(byteBuffer.array());
PdfStamper s = new PdfStamper(r,os);
AcroFields fs = s.getAcroFields();
Map<String, Object> hm = UtilGenerics.checkMap(fs.getFields());
s.setFormFlattening(true);
for (String fieldName : hm.keySet()) {
//AcroFields.Item item = fs.getFieldItem(fieldName);
//int type = fs.getFieldType(fieldName);
String value = fs.getField(fieldName);
GenericValue surveyQuestionAndAppl = EntityQuery.use(delegator).from("SurveyQuestionAndAppl")
.where("surveyId", surveyId,
"externalFieldRef", fieldName)
.queryFirst();
if (surveyQuestionAndAppl == null) {
Debug.logInfo("No question found for surveyId:" + surveyId + " and externalFieldRef:" + fieldName, module);
continue;
}
String surveyQuestionId = (String)surveyQuestionAndAppl.get("surveyQuestionId");
String surveyQuestionTypeId = (String)surveyQuestionAndAppl.get("surveyQuestionTypeId");
GenericValue surveyResponseAnswer = delegator.makeValue("SurveyResponseAnswer", UtilMisc.toMap("surveyResponseId", surveyResponseId, "surveyQuestionId", surveyQuestionId));
if (surveyQuestionTypeId ==null || surveyQuestionTypeId.equals("TEXT_SHORT")) {
surveyResponseAnswer.set("textResponse", value);
}
delegator.create(surveyResponseAnswer);
}
s.close();
} catch (GenericEntityException e) {
Debug.logError(e, "Error generating PDF: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale));
} catch (GeneralException e) {
Debug.logError(e, "Error generating PDF: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.getMessage()), locale));
} catch (Exception e) {
Debug.logError(e, "Error generating PDF: " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentPDFGeneratingError", UtilMisc.toMap("errorString", e.toString()), locale));
}
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("surveyResponseId", surveyResponseId);
return results;
}
/**
*/
public static Map<String, Object> getAcroFieldsFromPdf(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> acroFieldMap = new HashMap<String, Object>();
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
Delegator delegator = dctx.getDelegator();
ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
PdfReader r = new PdfReader(byteBuffer.array());
PdfStamper s = new PdfStamper(r,os);
AcroFields fs = s.getAcroFields();
Map<String, Object> map = UtilGenerics.checkMap(fs.getFields());
s.setFormFlattening(true);
// Debug code to get the values for setting TDP
// String[] sa = fs.getAppearanceStates("TDP");
// for (int i=0;i<sa.length;i++)
// Debug.logInfo("Appearance="+sa[i]);
for (String fieldName : map.keySet()) {
String parmValue = fs.getField(fieldName);
acroFieldMap.put(fieldName, parmValue);
}
} catch (DocumentException e) {
System.err.println(e.getMessage());
return ServiceUtil.returnError(e.getMessage());
} catch (GeneralException e) {
System.err.println(e.getMessage());
return ServiceUtil.returnError(e.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
return ServiceUtil.returnError(ioe.getMessage());
}
Map<String, Object> results = ServiceUtil.returnSuccess();
results.put("acroFieldMap", acroFieldMap);
return results;
}
/**
*/
public static Map<String, Object> setAcroFields(DispatchContext dctx, Map<String, ? extends Object> context) {
Map<String, Object> results = ServiceUtil.returnSuccess();
Delegator delegator = dctx.getDelegator();
try {
Map<String, Object> acroFieldMap = UtilGenerics.checkMap(context.get("acroFieldMap"));
ByteBuffer byteBuffer = getInputByteBuffer(context, delegator);
PdfReader r = new PdfReader(byteBuffer.array());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfStamper s = new PdfStamper(r, baos);
AcroFields fs = s.getAcroFields();
Map<String, Object> map = UtilGenerics.checkMap(fs.getFields());
s.setFormFlattening(true);
// Debug code to get the values for setting TDP
// String[] sa = fs.getAppearanceStates("TDP");
// for (int i=0;i<sa.length;i++)
// Debug.logInfo("Appearance="+sa[i]);
for (String fieldName : map.keySet()) {
String fieldValue = fs.getField(fieldName);
Object obj = acroFieldMap.get(fieldName);
if (obj instanceof Date) {
Date d=(Date)obj;
fieldValue=UtilDateTime.toDateString(d);
} else if (obj instanceof Long) {
Long lg=(Long)obj;
fieldValue=lg.toString();
} else if (obj instanceof Integer) {
Integer ii=(Integer)obj;
fieldValue=ii.toString();
} else {
fieldValue=(String)obj;
}
if (UtilValidate.isNotEmpty(fieldValue)) {
fs.setField(fieldName, fieldValue);
}
}
s.close();
baos.close();
ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
results.put("outByteBuffer", outByteBuffer);
} catch (DocumentException e) {
System.err.println(e.getMessage());
results = ServiceUtil.returnError(e.getMessage());
} catch (GeneralException e) {
System.err.println(e.getMessage());
results = ServiceUtil.returnError(e.getMessage());
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
results = ServiceUtil.returnError(e.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
results = ServiceUtil.returnError(ioe.getMessage());
} catch (Exception ioe) {
System.err.println(ioe.getMessage());
results = ServiceUtil.returnError(ioe.getMessage());
}
return results;
}
/**
*/
public static Map<String, Object> buildPdfFromSurveyResponse(DispatchContext dctx, Map<String, ? extends Object> rcontext) {
Map<String, Object> context = UtilMisc.makeMapWritable(rcontext);
Delegator delegator = dctx.getDelegator();
//LocalDispatcher dispatcher = dctx.getDispatcher();
Map<String, Object> results = ServiceUtil.returnSuccess();
String surveyResponseId = (String)context.get("surveyResponseId");
String contentId = (String)context.get("contentId");
String surveyId = null;
Document document = new Document();
try {
if (UtilValidate.isNotEmpty(surveyResponseId)) {
GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
if (surveyResponse != null) {
surveyId = surveyResponse.getString("surveyId");
}
}
if (UtilValidate.isNotEmpty(surveyId) && UtilValidate.isEmpty(contentId)) {
GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
if (survey != null) {
String acroFormContentId = survey.getString("acroFormContentId");
if (UtilValidate.isNotEmpty(acroFormContentId)) {
context.put("contentId", acroFormContentId);
}
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
List<GenericValue> responses = EntityQuery.use(delegator).from("SurveyResponseAnswer").where("surveyResponseId", surveyResponseId).queryList();
for (GenericValue surveyResponseAnswer : responses) {
String value = null;
String surveyQuestionId = (String) surveyResponseAnswer.get("surveyQuestionId");
GenericValue surveyQuestion = EntityQuery.use(delegator).from("SurveyQuestion").where("surveyQuestionId", surveyQuestionId).queryOne();
String questionType = surveyQuestion.getString("surveyQuestionTypeId");
// DEJ20060227 this isn't used, if needed in the future should get from SurveyQuestionAppl.externalFieldRef String fieldName = surveyQuestion.getString("description");
if ("OPTION".equals(questionType)) {
value = surveyResponseAnswer.getString("surveyOptionSeqId");
} else if ("BOOLEAN".equals(questionType)) {
value = surveyResponseAnswer.getString("booleanResponse");
} else if ("NUMBER_LONG".equals(questionType) || "NUMBER_CURRENCY".equals(questionType) || "NUMBER_FLOAT".equals(questionType)) {
Double num = surveyResponseAnswer.getDouble("numericResponse");
if (num != null) {
value = num.toString();
}
} else if ("SEPERATOR_LINE".equals(questionType) || "SEPERATOR_TEXT".equals(questionType)) {
// not really a question; ingore completely
} else {
value = surveyResponseAnswer.getString("textResponse");
}
Chunk chunk = new Chunk(surveyQuestion.getString("question") + ": " + value);
Paragraph p = new Paragraph(chunk);
document.add(p);
}
ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray());
results.put("outByteBuffer", outByteBuffer);
} catch (GenericEntityException e) {
System.err.println(e.getMessage());
results = ServiceUtil.returnError(e.getMessage());
} catch (DocumentException e) {
System.err.println(e.getMessage());
results = ServiceUtil.returnError(e.getMessage());
}
return results;
}
/**
* Returns list of maps with "question"->SurveyQuestion and "response"->SurveyResponseAnswer
*/
public static Map<String, Object> buildSurveyQuestionsAndAnswers(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
//LocalDispatcher dispatcher = dctx.getDispatcher();
Map<String, Object> results = ServiceUtil.returnSuccess();
String surveyResponseId = (String)context.get("surveyResponseId");
List<Object> qAndA = new LinkedList<Object>();
try {
List<GenericValue> responses = EntityQuery.use(delegator).from("SurveyResponseAnswer").where("surveyResponseId", surveyResponseId).queryList();
for (GenericValue surveyResponseAnswer : responses) {
String surveyQuestionId = (String) surveyResponseAnswer.get("surveyQuestionId");
GenericValue surveyQuestion = EntityQuery.use(delegator).from("SurveyQuestion").where("surveyQuestionId", surveyQuestionId).queryOne();
qAndA.add(UtilMisc.toMap("question", surveyQuestion, "response", surveyResponseAnswer));
}
results.put("questionsAndAnswers", qAndA);
} catch (GenericEntityException e) {
System.err.println(e.getMessage());
results = ServiceUtil.returnError(e.getMessage());
}
return results;
}
/**
*/
public static Map<String, Object> setAcroFieldsFromSurveyResponse(DispatchContext dctx, Map<String, ? extends Object> context) {
Delegator delegator = dctx.getDelegator();
LocalDispatcher dispatcher = dctx.getDispatcher();
Map<String, Object> results = ServiceUtil.returnSuccess();
Map<String, Object> acroFieldMap = new HashMap<String, Object>();
String surveyResponseId = (String)context.get("surveyResponseId");
String acroFormContentId = null;
try {
String surveyId = null;
if (UtilValidate.isNotEmpty(surveyResponseId)) {
GenericValue surveyResponse = EntityQuery.use(delegator).from("SurveyResponse").where("surveyResponseId", surveyResponseId).queryOne();
if (surveyResponse != null) {
surveyId = surveyResponse.getString("surveyId");
}
}
if (UtilValidate.isNotEmpty(surveyId)) {
GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).queryOne();
if (survey != null) {
acroFormContentId = survey.getString("acroFormContentId");
}
}
List<GenericValue> responses = EntityQuery.use(delegator).from("SurveyResponseAnswer").where("surveyResponseId", surveyResponseId).queryList();
for (GenericValue surveyResponseAnswer : responses) {
String value = null;
String surveyQuestionId = (String) surveyResponseAnswer.get("surveyQuestionId");
GenericValue surveyQuestion = EntityQuery.use(delegator).from("SurveyQuestion").where("surveyQuestionId", surveyQuestionId).cache().queryOne();
GenericValue surveyQuestionAppl = EntityQuery.use(delegator).from("SurveyQuestionAppl")
.where("surveyId", surveyId,
"surveyQuestionId", surveyQuestionId)
.orderBy("-fromDate")
.filterByDate().cache().queryFirst();
String questionType = surveyQuestion.getString("surveyQuestionTypeId");
String fieldName = surveyQuestionAppl.getString("externalFieldRef");
if ("OPTION".equals(questionType)) {
value = surveyResponseAnswer.getString("surveyOptionSeqId");
} else if ("BOOLEAN".equals(questionType)) {
value = surveyResponseAnswer.getString("booleanResponse");
} else if ("NUMBER_LONG".equals(questionType) || "NUMBER_CURRENCY".equals(questionType) || "NUMBER_FLOAT".equals(questionType)) {
Double num = surveyResponseAnswer.getDouble("numericResponse");
if (num != null) {
value = num.toString();
}
} else if ("SEPERATOR_LINE".equals(questionType) || "SEPERATOR_TEXT".equals(questionType)) {
// not really a question; ingore completely
} else {
value = surveyResponseAnswer.getString("textResponse");
}
acroFieldMap.put(fieldName, value);
}
} catch (GenericEntityException e) {
System.err.println(e.getMessage());
return ServiceUtil.returnError(e.getMessage());
}
try {
ModelService modelService = dispatcher.getDispatchContext().getModelService("setAcroFields");
Map<String, Object> ctx = modelService.makeValid(context, "IN");
ctx.put("acroFieldMap", acroFieldMap);
ctx.put("contentId", acroFormContentId);
Map<String, Object> map = dispatcher.runSync("setAcroFields", ctx);
if (ServiceUtil.isError(map)) {
return ServiceUtil.returnError(ServiceUtil.makeErrorMessage(map, null, null, null, null));
}
String pdfFileNameOut = (String) context.get("pdfFileNameOut");
ByteBuffer outByteBuffer = (ByteBuffer) map.get("outByteBuffer");
results.put("outByteBuffer", outByteBuffer);
if (UtilValidate.isNotEmpty(pdfFileNameOut)) {
FileOutputStream fos = new FileOutputStream(pdfFileNameOut);
fos.write(outByteBuffer.array());
fos.close();
}
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
results = ServiceUtil.returnError(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
results = ServiceUtil.returnError(e.getMessage());
} catch (GenericServiceException e) {
System.err.println(e.getMessage());
results = ServiceUtil.returnError(e.getMessage());
}
return results;
}
public static ByteBuffer getInputByteBuffer(Map<String, ? extends Object> context, Delegator delegator) throws GeneralException {
ByteBuffer inputByteBuffer = (ByteBuffer)context.get("inputByteBuffer");
if (inputByteBuffer == null) {
String pdfFileNameIn = (String)context.get("pdfFileNameIn");
String contentId = (String)context.get("contentId");
if (UtilValidate.isNotEmpty(pdfFileNameIn)) {
try {
FileInputStream fis = new FileInputStream(pdfFileNameIn);
int c;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((c = fis.read()) != -1) baos.write(c);
inputByteBuffer = ByteBuffer.wrap(baos.toByteArray());
} catch (FileNotFoundException e) {
throw(new GeneralException(e.getMessage()));
} catch (IOException e) {
throw(new GeneralException(e.getMessage()));
}
} else if (UtilValidate.isNotEmpty(contentId)) {
try {
Locale locale = (Locale)context.get("locale");
String https = (String)context.get("https");
String webSiteId = (String)context.get("webSiteId");
String rootDir = (String)context.get("rootDir");
GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
String dataResourceId = content.getString("dataResourceId");
inputByteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https, webSiteId, locale, rootDir);
} catch (GenericEntityException e) {
throw(new GeneralException(e.getMessage()));
} catch (IOException e) {
throw(new GeneralException(e.getMessage()));
}
}
}
return inputByteBuffer;
}
}
@@ -0,0 +1,71 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.survey;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.webapp.control.ConfigXMLReader;
import org.ofbiz.webapp.control.RequestHandler;
import org.ofbiz.webapp.control.ConfigXMLReader.RequestMap;
import org.ofbiz.webapp.control.WebAppConfigurationException;
import org.ofbiz.webapp.event.EventHandlerException;
/**
* SurveyEvents Class
*/
public class SurveyEvents {
public static final String module = SurveyEvents.class.getName();
public static String createSurveyResponseAndRestoreParameters(HttpServletRequest request, HttpServletResponse response) {
// Call createSurveyResponse as an event, easier to setup and ensures parameter security
ConfigXMLReader.Event createSurveyResponseEvent = new ConfigXMLReader.Event("service", null, "createSurveyResponse", true);
RequestHandler rh = (RequestHandler) request.getAttribute("_REQUEST_HANDLER_");
ConfigXMLReader.ControllerConfig controllerConfig = rh.getControllerConfig();
String requestUri = (String) request.getAttribute("thisRequestUri");
RequestMap requestMap = null;
try {
requestMap = controllerConfig.getRequestMapMap().get(requestUri);
} catch (WebAppConfigurationException e) {
Debug.logError(e, "Exception thrown while parsing controller.xml file: ", module);
}
String eventResponse = null;
try {
eventResponse = rh.runEvent(request, response, createSurveyResponseEvent, requestMap, null);
} catch (EventHandlerException e) {
Debug.logError(e, module);
return "error";
}
if (!"success".equals(eventResponse)) {
return eventResponse;
}
// Check for an incoming _ORIG_PARAM_MAP_ID_, if present get the session stored parameter map and insert it's entries as request attributes
Map<String, Object> combinedMap = UtilHttp.getCombinedMap(request);
if (combinedMap.containsKey("_ORIG_PARAM_MAP_ID_")) {
String origParamMapId = (String) combinedMap.get("_ORIG_PARAM_MAP_ID_");
UtilHttp.restoreStashedParameterMap(request, origParamMapId);
}
return "success";
}
}
@@ -0,0 +1,755 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.survey;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.ofbiz.base.location.FlexibleLocation;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityOperator;
import org.ofbiz.entity.transaction.TransactionUtil;
import org.ofbiz.entity.util.EntityListIterator;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
* Survey Wrapper - Class to render survey forms
*/
public class SurveyWrapper {
public static final String module = SurveyWrapper.class.getName();
protected Delegator delegator = null;
protected String responseId = null;
protected String partyId = null;
protected String surveyId = null;
protected Map<String, Object> templateContext = null;
protected Map<String, Object> passThru = null;
protected Map<String, Object> defaultValues = null;
protected boolean edit = false;
protected SurveyWrapper() {}
public SurveyWrapper(Delegator delegator, String responseId, String partyId, String surveyId, Map<String, Object> passThru, Map<String, Object> defaultValues) {
this.delegator = delegator;
this.responseId = responseId;
this.partyId = partyId;
this.surveyId = surveyId;
this.setPassThru(passThru);
this.setDefaultValues(defaultValues);
this.checkParameters();
}
public SurveyWrapper(Delegator delegator, String responseId, String partyId, String surveyId, Map<String, Object> passThru) {
this(delegator, responseId, partyId, surveyId, passThru, null);
}
public SurveyWrapper(Delegator delegator, String surveyId) {
this(delegator, null, null, surveyId, null);
}
protected void checkParameters() {
if (delegator == null || surveyId == null) {
throw new IllegalArgumentException("Missing one or more required parameters (delegator, surveyId)");
}
}
/**
* Sets the pass-thru values (hidden form fields)
* @param passThru
*/
public void setPassThru(Map<String, Object> passThru) {
if (passThru != null) {
this.passThru = new HashMap<String, Object>();
this.passThru.putAll(passThru);
}
}
/**
* Sets the default values
* @param defaultValues
*/
public void setDefaultValues(Map<String, Object> defaultValues) {
if (defaultValues != null) {
this.defaultValues = new HashMap<String, Object>();
this.defaultValues.putAll(defaultValues);
}
}
/**
* Adds an object to the FTL survey template context
* @param name
* @param value
*/
public void addToTemplateContext(String name, Object value) {
if (templateContext == null) {
templateContext = new HashMap<String, Object>();
}
templateContext.put(name, value);
}
/**
* Removes an object from the FTL survey template context
* @param name
*/
public void removeFromTemplateContext(String name) {
if (templateContext != null)
templateContext.remove(name);
}
/**
* Renders the Survey
* @return Writer object from the parsed Freemarker Template
* @throws SurveyWrapperException
*/
public Writer render(String templatePath) throws SurveyWrapperException {
URL templateUrl = null;
try {
templateUrl = FlexibleLocation.resolveLocation(templatePath);
} catch (MalformedURLException e) {
throw new SurveyWrapperException(e);
}
if (templateUrl == null) {
String errMsg = "Problem getting the template for Survey from URL: " + templatePath;
Debug.logError(errMsg, module);
throw new IllegalArgumentException(errMsg);
}
Writer writer = new StringWriter();
this.render(templateUrl, writer);
return writer;
}
/**
* Renders the Survey
* @param templateUrl the template URL
* @param writer the write
* @throws SurveyWrapperException
*/
public void render(URL templateUrl, Writer writer) throws SurveyWrapperException {
String responseId = this.getThisResponseId();
GenericValue survey = this.getSurvey();
List<GenericValue> surveyQuestionAndAppls = this.getSurveyQuestionAndAppls();
Map<String, Object> results = this.getResults(surveyQuestionAndAppls);
Map<String, Object> currentAnswers = null;
if (responseId != null && canUpdate()) {
currentAnswers = this.getResponseAnswers(responseId);
} else {
currentAnswers = this.getResponseAnswers(null);
}
Map<String, Object> sqaaWithColIdListByMultiRespId = new HashMap<String, Object>();
for (GenericValue surveyQuestionAndAppl : surveyQuestionAndAppls) {
String surveyMultiRespColId = surveyQuestionAndAppl.getString("surveyMultiRespColId");
if (UtilValidate.isNotEmpty(surveyMultiRespColId)) {
String surveyMultiRespId = surveyQuestionAndAppl.getString("surveyMultiRespId");
UtilMisc.addToListInMap(surveyQuestionAndAppl, sqaaWithColIdListByMultiRespId, surveyMultiRespId);
}
}
if (templateContext == null) {
templateContext = new HashMap<String, Object>();
}
templateContext.put("partyId", partyId);
templateContext.put("survey", survey);
templateContext.put("surveyResults", results);
templateContext.put("surveyQuestionAndAppls", surveyQuestionAndAppls);
templateContext.put("sqaaWithColIdListByMultiRespId", sqaaWithColIdListByMultiRespId);
templateContext.put("alreadyShownSqaaPkWithColId", new HashSet());
templateContext.put("surveyAnswers", currentAnswers);
templateContext.put("surveyResponseId", responseId);
templateContext.put("sequenceSort", UtilMisc.toList("sequenceNum"));
templateContext.put("additionalFields", passThru);
templateContext.put("defaultValues", defaultValues);
templateContext.put("delegator", this.delegator);
templateContext.put("locale", Locale.getDefault());
Template template = this.getTemplate(templateUrl);
try {
FreeMarkerWorker.renderTemplate(template, templateContext, writer);
} catch (TemplateException e) {
Debug.logError(e, "Error rendering Survey with template at [" + templateUrl.toExternalForm() + "]", module);
} catch (IOException e) {
Debug.logError(e, "Error rendering Survey with template at [" + templateUrl.toExternalForm() + "]", module);
}
}
// returns the FTL Template object
// Note: the template will not be cached
protected Template getTemplate(URL templateUrl) {
Configuration config = FreeMarkerWorker.getDefaultOfbizConfig();
Template template = null;
try {
InputStream templateStream = templateUrl.openStream();
InputStreamReader templateReader = new InputStreamReader(templateStream);
template = new Template(templateUrl.toExternalForm(), templateReader, config);
} catch (IOException e) {
Debug.logError(e, "Unable to get template from URL :" + templateUrl.toExternalForm(), module);
}
return template;
}
public void setEdit(boolean edit) {
this.edit = edit;
}
// returns the GenericValue object for the current Survey
public GenericValue getSurvey() {
GenericValue survey = null;
try {
survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get Survey : " + surveyId, module);
}
return survey;
}
public String getSurveyName() {
GenericValue survey = this.getSurvey();
if (survey != null) {
return survey.getString("surveyName");
}
return "";
}
// true if we can update this survey
public boolean canUpdate() {
if (this.edit) {
return true;
}
GenericValue survey = this.getSurvey();
if (!"Y".equals(survey.getString("allowMultiple")) && !"Y".equals(survey.getString("allowUpdate"))) {
return false;
}
return true;
}
public boolean canRespond() {
String responseId = this.getThisResponseId();
if (responseId == null) {
return true;
} else {
GenericValue survey = this.getSurvey();
if ("Y".equals(survey.getString("allowMultiple"))) {
return true;
}
}
return false;
}
// returns a list of SurveyQuestions (in order by sequence number) for the current Survey
public List<GenericValue> getSurveyQuestionAndAppls() {
List<GenericValue> questions = new LinkedList<GenericValue>();
try {
questions = EntityQuery.use(delegator).from("SurveyQuestionAndAppl")
.where("surveyId", surveyId)
.orderBy("sequenceNum", "surveyMultiRespColId")
.filterByDate().cache().queryList();
} catch (GenericEntityException e) {
Debug.logError(e, "Unable to get questions for survey : " + surveyId, module);
}
return questions;
}
// returns the most current SurveyResponse ID for a survey; null if no party is found
protected String getThisResponseId() {
if (responseId != null) {
return responseId;
}
if (partyId == null) {
return null;
}
String responseId = null;
List<GenericValue> responses = null;
try {
responses = EntityQuery.use(delegator).from("SurveyResponse")
.where("surveyId", surveyId, "partyId", partyId)
.orderBy("-lastModifiedDate")
.queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (UtilValidate.isNotEmpty(responses)) {
GenericValue response = EntityUtil.getFirst(responses);
responseId = response.getString("surveyResponseId");
if (responses.size() > 1) {
Debug.logWarning("More then one response found for survey : " + surveyId + " by party : " + partyId + " using most current", module);
}
}
return responseId;
}
protected void setThisResponseId(String responseId) {
this.responseId = responseId;
}
public long getNumberResponses() throws SurveyWrapperException {
long responses = 0;
try {
responses = EntityQuery.use(delegator).from("SurveyResponse").where("surveyId", surveyId).queryCount();
} catch (GenericEntityException e) {
throw new SurveyWrapperException(e);
}
return responses;
}
public List<GenericValue> getSurveyResponses(GenericValue question) throws SurveyWrapperException {
List<GenericValue> responses = null;
try {
responses = EntityQuery.use(delegator).from("SurveyResponse").where("surveyQuestionId", question.get("surveyQuestionId")).queryList();
} catch (GenericEntityException e) {
throw new SurveyWrapperException(e);
}
return responses;
}
// returns a Map of answers keyed on SurveyQuestion ID from the most current SurveyResponse ID
public Map<String, Object> getResponseAnswers(String responseId) throws SurveyWrapperException {
Map<String, Object> answerMap = new HashMap<String, Object>();
if (responseId != null) {
List<GenericValue> answers = null;
try {
answers = EntityQuery.use(delegator).from("SurveyResponseAnswer").where("surveyResponseId", responseId).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
if (UtilValidate.isNotEmpty(answers)) {
for (GenericValue answer : answers) {
answerMap.put(answer.getString("surveyQuestionId"), answer);
}
}
}
// get the pass-thru (posted form data)
if (UtilValidate.isNotEmpty(passThru)) {
for (String key : passThru.keySet()) {
if (key.toUpperCase().startsWith("ANSWERS_")) {
int splitIndex = key.indexOf('_');
String questionId = key.substring(splitIndex+1);
Map<String, Object> thisAnswer = new HashMap<String, Object>();
String answer = (String) passThru.remove(key);
thisAnswer.put("booleanResponse", answer);
thisAnswer.put("currencyResponse", answer);
thisAnswer.put("floatResponse", answer);
thisAnswer.put("numericResponse", answer);
thisAnswer.put("textResponse", answer);
thisAnswer.put("surveyOptionSeqId", answer);
// this is okay since only one will be looked at
answerMap.put(questionId, thisAnswer);
}
}
}
return answerMap;
}
public List<GenericValue> getQuestionResponses(GenericValue question, int startIndex, int number) throws SurveyWrapperException {
List<GenericValue> resp = null;
boolean beganTransaction = false;
try {
beganTransaction = TransactionUtil.begin();
int maxRows = startIndex + number;
EntityListIterator eli = this.getEli(question, maxRows);
if (startIndex > 0 && number > 0) {
resp = eli.getPartialList(startIndex, number);
} else {
resp = eli.getCompleteList();
}
eli.close();
} catch (GenericEntityException e) {
try {
// only rollback the transaction if we started one...
TransactionUtil.rollback(beganTransaction, "Error getting survey question responses", e);
} catch (GenericEntityException e2) {
Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
}
throw new SurveyWrapperException(e);
} finally {
try {
// only commit the transaction if we started one...
TransactionUtil.commit(beganTransaction);
} catch (GenericEntityException e) {
throw new SurveyWrapperException(e);
//Debug.logError(e, "Could not commit transaction: " + e.toString(), module);
}
}
return resp;
}
public Map<String, Object> getResults(List<GenericValue> questions) throws SurveyWrapperException {
Map<String, Object> questionResults = new HashMap<String, Object>();
if (questions != null) {
for (GenericValue question : questions) {
Map<String, Object> results = getResultInfo(question);
if (results != null) {
questionResults.put(question.getString("surveyQuestionId"), results);
}
}
}
return questionResults;
}
// returns a map of question reqsults
public Map<String, Object> getResultInfo(GenericValue question) throws SurveyWrapperException {
Map<String, Object> resultMap = new HashMap<String, Object>();
// special keys in the result:
// "_q_type" - question type (SurveyQuestionTypeId)
// "_a_type" - answer type ("boolean", "option", "long", "double", "text")
// "_total" - number of total responses (all types)
// "_tally" - tally of all response values (number types)
// "_average" - average of all response values (number types)
// "_yes_total" - number of 'Y' (true) reponses (boolean type)
// "_no_total" - number of 'N' (false) responses (boolean type)
// "_yes_percent" - number of 'Y' (true) reponses (boolean type)
// "_no_percent" - number of 'N' (false) responses (boolean type)
// [optionId] - Map containing '_total, _percent' keys (option type)
String questionType = question.getString("surveyQuestionTypeId");
resultMap.put("_q_type", questionType);
// call the proper method based on the question type
// note this will need to be updated as new types are added
if ("OPTION".equals(questionType)) {
Map<String, Object> thisResult = getOptionResult(question);
if (thisResult != null) {
Long questionTotal = (Long) thisResult.remove("_total");
if (questionTotal == null) {
questionTotal = Long.valueOf(0);
}
// set the total responses
resultMap.put("_total", questionTotal);
// create the map of option info ("_total", "_percent")
for (String optId : thisResult.keySet()) {
Map<String, Object> optMap = new HashMap<String, Object>();
Long optTotal = (Long) thisResult.get(optId);
if (optTotal == null) {
optTotal = Long.valueOf(0);
}
Long percent = Long.valueOf((long)(((double)optTotal.longValue() / (double)questionTotal.longValue()) * 100));
optMap.put("_total", optTotal);
optMap.put("_percent", percent);
resultMap.put(optId, optMap);
}
resultMap.put("_a_type", "option");
}
} else if ("BOOLEAN".equals(questionType)) {
long[] thisResult = getBooleanResult(question);
long yesPercent = thisResult[1] > 0 ? (long)(((double)thisResult[1] / (double)thisResult[0]) * 100) : 0;
long noPercent = thisResult[2] > 0 ? (long)(((double)thisResult[2] / (double)thisResult[0]) * 100) : 0;
resultMap.put("_total", Long.valueOf(thisResult[0]));
resultMap.put("_yes_total", Long.valueOf(thisResult[1]));
resultMap.put("_no_total", Long.valueOf(thisResult[2]));
resultMap.put("_yes_percent", Long.valueOf(yesPercent));
resultMap.put("_no_percent", Long.valueOf(noPercent));
resultMap.put("_a_type", "boolean");
} else if ("NUMBER_LONG".equals(questionType)) {
double[] thisResult = getNumberResult(question, 1);
resultMap.put("_total", Long.valueOf((long)thisResult[0]));
resultMap.put("_tally", Long.valueOf((long)thisResult[1]));
resultMap.put("_average", Long.valueOf((long)thisResult[2]));
resultMap.put("_a_type", "long");
} else if ("NUMBER_CURRENCY".equals(questionType)) {
double[] thisResult = getNumberResult(question, 2);
resultMap.put("_total", Long.valueOf((long)thisResult[0]));
resultMap.put("_tally", Double.valueOf(thisResult[1]));
resultMap.put("_average", Double.valueOf(thisResult[2]));
resultMap.put("_a_type", "double");
} else if ("NUMBER_FLOAT".equals(questionType)) {
double[] thisResult = getNumberResult(question, 3);
resultMap.put("_total", Long.valueOf((long)thisResult[0]));
resultMap.put("_tally", Double.valueOf(thisResult[1]));
resultMap.put("_average", Double.valueOf(thisResult[2]));
resultMap.put("_a_type", "double");
} else if ("SEPERATOR_LINE".equals(questionType) || "SEPERATOR_TEXT".equals(questionType)) {
// not really a question; ingore completely
return null;
} else {
// default is text
resultMap.put("_total", Long.valueOf(getTextResult(question)));
resultMap.put("_a_type", "text");
}
return resultMap;
}
private long[] getBooleanResult(GenericValue question) throws SurveyWrapperException {
boolean beganTransaction = false;
try {
beganTransaction = TransactionUtil.begin();
long[] result = { 0, 0, 0 };
// index 0 = total responses
// index 1 = total yes
// index 2 = total no
EntityListIterator eli = this.getEli(question, -1);
if (eli != null) {
GenericValue value;
while (((value = eli.next()) != null)) {
if ("Y".equalsIgnoreCase(value.getString("booleanResponse"))) {
result[1]++;
} else {
result[2]++;
}
result[0]++; // increment the count
}
eli.close();
}
return result;
} catch (GenericEntityException e) {
try {
// only rollback the transaction if we started one...
TransactionUtil.rollback(beganTransaction, "Error getting survey question responses Boolean result", e);
} catch (GenericEntityException e2) {
Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
}
throw new SurveyWrapperException(e);
} finally {
try {
// only commit the transaction if we started one...
TransactionUtil.commit(beganTransaction);
} catch (GenericEntityException e) {
throw new SurveyWrapperException(e);
//Debug.logError(e, "Could not commit transaction: " + e.toString(), module);
}
}
}
private double[] getNumberResult(GenericValue question, int type) throws SurveyWrapperException {
double[] result = { 0, 0, 0 };
// index 0 = total responses
// index 1 = tally
// index 2 = average
boolean beganTransaction = false;
try {
beganTransaction = TransactionUtil.begin();
EntityListIterator eli = this.getEli(question, -1);
if (eli != null) {
GenericValue value;
while (((value = eli.next()) != null)) {
switch (type) {
case 1:
Long n = value.getLong("numericResponse");
if (UtilValidate.isNotEmpty(n)) {
result[1] += n.longValue();
}
break;
case 2:
Double c = value.getDouble("currencyResponse");
if (UtilValidate.isNotEmpty(c)) {
result[1] += (((double) Math.round((c.doubleValue() - c.doubleValue()) * 100)) / 100);
}
break;
case 3:
Double f = value.getDouble("floatResponse");
if (UtilValidate.isNotEmpty(f)) {
result[1] += f.doubleValue();
}
break;
}
result[0]++; // increment the count
}
eli.close();
}
} catch (GenericEntityException e) {
try {
// only rollback the transaction if we started one...
TransactionUtil.rollback(beganTransaction, "Error getting survey question responses Number result", e);
} catch (GenericEntityException e2) {
Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
}
throw new SurveyWrapperException(e);
} finally {
try {
// only commit the transaction if we started one...
TransactionUtil.commit(beganTransaction);
} catch (GenericEntityException e) {
throw new SurveyWrapperException(e);
//Debug.logError(e, "Could not commit transaction: " + e.toString(), module);
}
}
// average
switch (type) {
case 1:
if (result[0] > 0)
result[2] = ((long) result[1]) / ((long) result[0]);
break;
case 2:
if (result[0] > 0)
result[2] = (((double) Math.round((result[1] / result[0]) * 100)) / 100);
break;
case 3:
if (result[0] > 0)
result[2] = result[1] / result[0];
break;
}
return result;
}
private long getTextResult(GenericValue question) throws SurveyWrapperException {
long result = 0;
try {
result = EntityQuery.use(delegator).from("SurveyResponseAndAnswer")
.where(makeEliCondition(question))
.queryCount();
} catch (GenericEntityException e) {
Debug.logError(e, module);
throw new SurveyWrapperException("Unable to get responses", e);
}
return result;
}
private Map<String, Object> getOptionResult(GenericValue question) throws SurveyWrapperException {
Map<String, Object> result = new HashMap<String, Object>();
long total = 0;
boolean beganTransaction = false;
try {
beganTransaction = TransactionUtil.begin();
EntityListIterator eli = this.getEli(question, -1);
if (eli != null) {
GenericValue value;
while (((value = eli.next()) != null)) {
String optionId = value.getString("surveyOptionSeqId");
if (UtilValidate.isNotEmpty(optionId)) {
Long optCount = (Long) result.remove(optionId);
if (optCount == null) {
optCount = Long.valueOf(1);
} else {
optCount = Long.valueOf(1 + optCount.longValue());
}
result.put(optionId, optCount);
total++; // increment the count
}
}
eli.close();
}
} catch (GenericEntityException e) {
try {
// only rollback the transaction if we started one...
TransactionUtil.rollback(beganTransaction, "Error getting survey question responses Option result", e);
} catch (GenericEntityException e2) {
Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
}
throw new SurveyWrapperException(e);
} finally {
try {
// only commit the transaction if we started one...
TransactionUtil.commit(beganTransaction);
} catch (GenericEntityException e) {
throw new SurveyWrapperException(e);
//Debug.logError(e, "Could not commit transaction: " + e.toString(), module);
}
}
result.put("_total", Long.valueOf(total));
return result;
}
private EntityCondition makeEliCondition(GenericValue question) {
return EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("surveyQuestionId",
EntityOperator.EQUALS, question.getString("surveyQuestionId")),
EntityCondition.makeCondition("surveyId", EntityOperator.EQUALS, surveyId)), EntityOperator.AND);
}
private EntityListIterator getEli(GenericValue question, int maxRows) throws GenericEntityException {
return EntityQuery.use(delegator).from("SurveyResponseAndAnswer")
.where(makeEliCondition(question))
.cursorScrollInsensitive()
.maxRows(maxRows)
.queryIterator();
}
@SuppressWarnings("serial")
protected class SurveyWrapperException extends GeneralException {
public SurveyWrapperException() {
super();
}
public SurveyWrapperException(String str) {
super(str);
}
public SurveyWrapperException(String str, Throwable nested) {
super(str, nested);
}
public SurveyWrapperException(Throwable nested) {
super(nested);
}
}
}
@@ -0,0 +1,198 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.view;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.sql.Timestamp;
import java.text.ParseException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.content.data.DataResourceWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.entity.util.EntityUtilProperties;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;
import org.ofbiz.webapp.view.AbstractViewHandler;
import org.ofbiz.webapp.view.ViewHandlerException;
import org.ofbiz.webapp.website.WebSiteWorker;
public class SimpleContentViewHandler extends AbstractViewHandler {
public static final String module = SimpleContentViewHandler.class.getName();
private String rootDir = null;
private String https = null;
private String defaultCharset = null;
public void init(ServletContext context) throws ViewHandlerException {
rootDir = context.getRealPath("/");
https = (String) context.getAttribute("https");
defaultCharset = context.getInitParameter("charset");
if (UtilValidate.isEmpty(defaultCharset)) {
defaultCharset = "UTF-8";
}
}
/**
* @see org.ofbiz.webapp.view.ViewHandler#render(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
*/
public void render(String name, String page, String info, String contentType, String encoding, HttpServletRequest request, HttpServletResponse response) throws ViewHandlerException {
LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
HttpSession session = request.getSession();
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
String contentId = request.getParameter("contentId");
String rootContentId = request.getParameter("rootContentId");
String mapKey = request.getParameter("mapKey");
String contentAssocTypeId = request.getParameter("contentAssocTypeId");
String fromDateStr = request.getParameter("fromDate");
String dataResourceId = request.getParameter("dataResourceId");
String contentRevisionSeqId = request.getParameter("contentRevisionSeqId");
String mimeTypeId = request.getParameter("mimeTypeId");
Locale locale = UtilHttp.getLocale(request);
String webSiteId = WebSiteWorker.getWebSiteId(request);
try {
if (Debug.verboseOn()) Debug.logVerbose("dataResourceId:" + dataResourceId, module);
Delegator delegator = (Delegator)request.getAttribute("delegator");
if (UtilValidate.isEmpty(dataResourceId)) {
if (UtilValidate.isEmpty(contentRevisionSeqId)) {
if (UtilValidate.isEmpty(mapKey) && UtilValidate.isEmpty(contentAssocTypeId)) {
if (UtilValidate.isNotEmpty(contentId)) {
GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
dataResourceId = content.getString("dataResourceId");
}
if (Debug.verboseOn()) Debug.logVerbose("dataResourceId:" + dataResourceId, module);
} else {
Timestamp fromDate = null;
if (UtilValidate.isNotEmpty(fromDateStr)) {
try {
fromDate = UtilDateTime.stringToTimeStamp(fromDateStr, null, locale);
} catch (ParseException e) {
fromDate = UtilDateTime.nowTimestamp();
}
}
List<String> assocList = null;
if (UtilValidate.isNotEmpty(contentAssocTypeId)) {
assocList = UtilMisc.toList(contentAssocTypeId);
}
GenericValue content = ContentWorker.getSubContent(delegator, contentId, mapKey, null, null, assocList, fromDate);
dataResourceId = content.getString("dataResourceId");
if (Debug.verboseOn()) Debug.logVerbose("dataResourceId:" + dataResourceId, module);
}
} else {
GenericValue contentRevisionItem = EntityQuery.use(delegator).from("ContentRevisionItem").where("contentId", rootContentId, "itemContentId", contentId, "contentRevisionSeqId", contentRevisionSeqId).cache().queryOne();
if (contentRevisionItem == null) {
throw new ViewHandlerException("ContentRevisionItem record not found for contentId=" + rootContentId
+ ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId);
}
dataResourceId = contentRevisionItem.getString("newDataResourceId");
if (Debug.verboseOn()) Debug.logVerbose("contentRevisionItem:" + contentRevisionItem, module);
if (Debug.verboseOn()) Debug.logVerbose("contentId=" + rootContentId + ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId, module);
if (Debug.verboseOn()) Debug.logVerbose("dataResourceId:" + dataResourceId, module);
}
}
if (UtilValidate.isNotEmpty(dataResourceId)) {
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne();
// DEJ20080717: why are we rendering the DataResource directly instead of rendering the content?
ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https, webSiteId, locale, rootDir);
ByteArrayInputStream bais = new ByteArrayInputStream(byteBuffer.array());
// setup chararcter encoding and content type
String charset = dataResource.getString("characterSetId");
if (UtilValidate.isEmpty(charset)) {
charset = defaultCharset;
}
if (UtilValidate.isEmpty(mimeTypeId)) {
mimeTypeId = DataResourceWorker.getMimeType(dataResource);
if ("text/html".equalsIgnoreCase(mimeTypeId)) {
mimeTypeId = "application/octet-stream";
}
}
// setup content type
String contentType2 = UtilValidate.isNotEmpty(mimeTypeId) ? mimeTypeId + "; charset=" +charset : contentType;
String fileName = null;
if (!UtilValidate.isEmpty(dataResource.getString("dataResourceName"))) {
fileName = dataResource.getString("dataResourceName").replace(" ", "_"); // spaces in filenames can be a problem
}
// see if data resource is public or not
String isPublic = dataResource.getString("isPublic");
if (UtilValidate.isEmpty(isPublic)) {
isPublic = "N";
}
// get the permission service required for streaming data; default is always the genericContentPermission
String permissionService = EntityUtilProperties.getPropertyValue("content", "stream.permission.service", "genericContentPermission", delegator);
// not public check security
if (!"Y".equalsIgnoreCase(isPublic)) {
// do security check
Map<String, ? extends Object> permSvcCtx = UtilMisc.toMap("userLogin", userLogin, "locale", locale, "mainAction", "VIEW", "contentId", contentId);
Map<String, Object> permSvcResp;
try {
permSvcResp = dispatcher.runSync(permissionService, permSvcCtx);
} catch (GenericServiceException e) {
Debug.logError(e, module);
request.setAttribute("_ERROR_MESSAGE_", e.getMessage());
throw new ViewHandlerException(e.getMessage());
}
if (ServiceUtil.isError(permSvcResp)) {
String errorMsg = ServiceUtil.getErrorMessage(permSvcResp);
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
throw new ViewHandlerException(errorMsg);
}
// no service errors; now check the actual response
Boolean hasPermission = (Boolean) permSvcResp.get("hasPermission");
if (!hasPermission.booleanValue()) {
String errorMsg = (String) permSvcResp.get("failMessage");
Debug.logError(errorMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errorMsg);
throw new ViewHandlerException(errorMsg);
}
}
UtilHttp.streamContentToBrowser(response, bais, byteBuffer.limit(), contentType2, fileName);
}
} catch (GenericEntityException e) {
throw new ViewHandlerException(e.getMessage());
} catch (IOException e) {
throw new ViewHandlerException(e.getMessage());
} catch (GeneralException e) {
throw new ViewHandlerException(e.getMessage());
}
}
}
@@ -0,0 +1,219 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.content.content.PermissionRecorder;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entityext.permission.EntityPermissionChecker;
import org.ofbiz.security.Security;
import org.ofbiz.service.ModelService;
import org.ofbiz.webapp.ftl.LoopWriter;
import freemarker.core.Environment;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;
import freemarker.template.TransformControl;
/**
* CheckPermissionTransform - Freemarker Transform for URLs (links)
*/
public class CheckPermissionTransform implements TemplateTransformModel {
public static final String module = CheckPermissionTransform.class.getName();
public static final String [] saveKeyNames = {"globalNodeTrail", "nodeTrail", "mode", "purposeTypeId", "statusId", "entityOperation", "targetOperation" };
public static final String [] removeKeyNames = {};
/**
* @deprecated use FreeMarkerWorker.getWrappedObject()
* A wrapper for the FreeMarkerWorker version.
*/
@Deprecated
public static Object getWrappedObject(String varName, Environment env) {
return FreeMarkerWorker.getWrappedObject(varName, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, ? extends Object> args, String key, Environment env) {
return FreeMarkerWorker.getArg(args, key, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, ? extends Object> args, String key, Map<String, ? extends Object> ctx) {
return FreeMarkerWorker.getArg(args, key, ctx);
}
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
final Map<String, Object> templateCtx = FreeMarkerWorker.createEnvironmentMap(env);
//FreeMarkerWorker.convertContext(templateCtx);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
FreeMarkerWorker.getSiteParameters(request, templateCtx);
FreeMarkerWorker.overrideWithArgs(templateCtx, args);
final String mode = (String)templateCtx.get("mode");
final String quickCheckContentId = (String)templateCtx.get("quickCheckContentId");
final Map<String, Object> savedValues = new HashMap<String, Object>();
//Debug.logInfo("in CheckPermission, contentId(1):" + templateCtx.get("contentId"),"");
//Debug.logInfo("in CheckPermission, subContentId(1):" + templateCtx.get("subContentId"),"");
return new LoopWriter(out) {
@Override
public void write(char cbuf[], int off, int len) {
buf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public int onStart() throws TemplateModelException, IOException {
List<Map<String, ? extends Object>> trail = UtilGenerics.checkList(templateCtx.get("globalNodeTrail"));
//String trailCsv = ContentWorker.nodeTrailToCsv(trail);
//Debug.logInfo("in CheckPermission, trailCsv(2):" + trailCsv,"");
//Debug.logInfo("in CheckPermission, contentId(2):" + templateCtx.get("contentId"),"");
//Debug.logInfo("in CheckPermission, subContentId(2):" + templateCtx.get("subContentId"),"");
GenericValue currentContent = null;
String contentAssocPredicateId = (String)templateCtx.get("contentAssocPredicateId");
String strNullThruDatesOnly = (String)templateCtx.get("nullThruDatesOnly");
Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && strNullThruDatesOnly.equalsIgnoreCase("true")) ? Boolean.TRUE : Boolean.FALSE;
GenericValue val = null;
try {
val = ContentWorker.getCurrentContent(delegator, trail, userLogin, templateCtx, nullThruDatesOnly, contentAssocPredicateId);
} catch (GeneralException e) {
throw new RuntimeException("Error getting current content. " + e.toString());
}
// final GenericValue view = val;
currentContent = val;
if (currentContent != null) {
//Debug.logInfo("in CheckPermission, currentContent(0):" + currentContent.get("contentId"),"");
}
if (currentContent == null) {
currentContent = delegator.makeValue("Content");
currentContent.put("ownerContentId", templateCtx.get("ownerContentId"));
}
//Debug.logInfo("in CheckPermission, currentContent(1):" + currentContent.get("contentId"),"");
Security security = null;
if (request != null) {
security = (Security) request.getAttribute("security");
}
String statusId = (String)currentContent.get("statusId");
String passedStatusId = (String)templateCtx.get("statusId");
List<String> statusList = StringUtil.split(passedStatusId, "|");
if (statusList == null) {
statusList = new LinkedList<String>();
}
if (UtilValidate.isNotEmpty(statusId) && !statusList.contains(statusId)) {
statusList.add(statusId);
}
String targetPurpose = (String)templateCtx.get("contentPurposeList");
List<String> purposeList = StringUtil.split(targetPurpose, "|");
String entityOperation = (String)templateCtx.get("entityOperation");
String targetOperation = (String)templateCtx.get("targetOperation");
if (UtilValidate.isEmpty(targetOperation)) {
if (UtilValidate.isNotEmpty(entityOperation)) {
targetOperation = "CONTENT" + entityOperation;
}
}
List<String> targetOperationList = StringUtil.split(targetOperation, "|");
if (targetOperationList.size() == 0) {
//Debug.logInfo("in CheckPermission, entityOperation:" + entityOperation,"");
//Debug.logInfo("in CheckPermission, templateCtx:" + templateCtx,"");
throw new IOException("targetOperationList has zero size.");
}
List<String> roleList = new LinkedList<String>();
String privilegeEnumId = (String)currentContent.get("privilegeEnumId");
Map<String, Object> results = EntityPermissionChecker.checkPermission(currentContent, statusList, userLogin, purposeList, targetOperationList, roleList, delegator, security, entityOperation, privilegeEnumId, quickCheckContentId);
boolean isError = ModelService.RESPOND_ERROR.equals(results.get(ModelService.RESPONSE_MESSAGE));
if (isError) {
throw new IOException(ModelService.RESPONSE_MESSAGE);
}
String permissionStatus = (String) results.get("permissionStatus");
if (UtilValidate.isEmpty(permissionStatus) || !permissionStatus.equals("granted")) {
String errorMessage = "Permission to add response is denied (2)";
PermissionRecorder recorder = (PermissionRecorder)results.get("permissionRecorder");
//Debug.logInfo("recorder(0):" + recorder, "");
if (recorder != null) {
String permissionMessage = recorder.toHtml();
//Debug.logInfo("permissionMessage(0):" + permissionMessage, "");
errorMessage += " \n " + permissionMessage;
}
templateCtx.put("permissionErrorMsg", errorMessage);
}
if (permissionStatus != null && permissionStatus.equalsIgnoreCase("granted")) {
FreeMarkerWorker.saveContextValues(templateCtx, saveKeyNames, savedValues);
if (mode == null || !mode.equalsIgnoreCase("not-equals"))
return TransformControl.EVALUATE_BODY;
else
return TransformControl.SKIP_BODY;
} else {
if (mode == null || !mode.equalsIgnoreCase("not-equals"))
return TransformControl.SKIP_BODY;
else
return TransformControl.EVALUATE_BODY;
}
}
@Override
public void close() throws IOException {
FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
String wrappedContent = buf.toString();
out.write(wrappedContent);
}
};
}
}
@@ -0,0 +1,192 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.service.LocalDispatcher;
import freemarker.core.Environment;
import freemarker.template.TemplateTransformModel;
//import com.clarkware.profiler.Profiler;
/**
* EditRenderSubContentCacheTransform - Freemarker Transform for URLs (links)
*
* This is an interactive FreeMarker tranform that allows the user to modify the contents that are placed within it.
*/
public class EditRenderSubContentCacheTransform implements TemplateTransformModel {
public static final String module = EditRenderSubContentCacheTransform.class.getName();
public static final String [] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"};
/**
* @deprecated use FreeMarkerWorker.getWrappedObject()
* A wrapper for the FreeMarkerWorker version.
*/
@Deprecated
public static Object getWrappedObject(String varName, Environment env) {
return FreeMarkerWorker.getWrappedObject(varName, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, ? extends Object> args, String key, Environment env) {
return FreeMarkerWorker.getArg(args, key, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, ? extends Object> args, String key, Map<String, ? extends Object> ctx) {
return FreeMarkerWorker.getArg(args, key, ctx);
}
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
final Map<String, Object> templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
FreeMarkerWorker.getSiteParameters(request, templateCtx);
FreeMarkerWorker.overrideWithArgs(templateCtx, args);
final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
List<Map<String, ? extends Object>> trail = UtilGenerics.checkList(templateCtx.get("globalNodeTrail"));
String contentAssocPredicateId = (String)templateCtx.get("contentAssocPredicateId");
String strNullThruDatesOnly = (String)templateCtx.get("nullThruDatesOnly");
Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && strNullThruDatesOnly.equalsIgnoreCase("true")) ? Boolean.TRUE :Boolean.FALSE;
GenericValue val = null;
try {
val = ContentWorker.getCurrentContent(delegator, trail, userLogin, templateCtx, nullThruDatesOnly, contentAssocPredicateId);
} catch (GeneralException e) {
throw new RuntimeException("Error getting current content. " + e.toString());
}
final GenericValue view = val;
String dataResourceId = null;
try {
dataResourceId = (String) view.get("drDataResourceId");
} catch (Exception e) {
dataResourceId = (String) view.get("dataResourceId");
}
String subContentIdSub = (String) view.get("contentId");
// This order is taken so that the dataResourceType can be overridden in the transform arguments.
String subDataResourceTypeId = (String)templateCtx.get("subDataResourceTypeId");
if (UtilValidate.isEmpty(subDataResourceTypeId)) {
try {
subDataResourceTypeId = (String) view.get("drDataResourceTypeId");
} catch (Exception e) {
// view may be "Content"
}
// TODO: If this value is still empty then it is probably necessary to get a value from
// the parent context. But it will already have one and it is the same context that is
// being passed.
}
// This order is taken so that the mimeType can be overridden in the transform arguments.
String mimeTypeId = ContentWorker.getMimeTypeId(delegator, view, templateCtx);
templateCtx.put("drDataResourceId", dataResourceId);
templateCtx.put("mimeTypeId", mimeTypeId);
templateCtx.put("dataResourceId", dataResourceId);
templateCtx.put("subContentIdSub", subContentIdSub);
templateCtx.put("subDataResourceTypeId", subDataResourceTypeId);
final Map<String, Object> savedValues = new HashMap<String, Object>();
FreeMarkerWorker.saveContextValues(templateCtx, saveKeyNames, savedValues);
return new Writer(out) {
@Override
public void write(char cbuf[], int off, int len) {
buf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
String wrappedContent = buf.toString();
// String editTemplate = (String)templateCtx.get("editTemplate");
// if (editTemplate != null && editTemplate.equalsIgnoreCase("true")) {
String wrapTemplateId = (String)templateCtx.get("wrapTemplateId");
if (UtilValidate.isNotEmpty(wrapTemplateId)) {
templateCtx.put("wrappedContent", wrappedContent);
//Map templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
Map<String, Object> templateRoot = null;
Map<String, Object> templateRootTemplate = UtilGenerics.checkMap(templateCtx.get("templateRootTemplate"));
if (templateRootTemplate == null) {
Map<String, Object> templateRootTmp = FreeMarkerWorker.createEnvironmentMap(env);
templateRoot = UtilMisc.makeMapWritable(templateRootTmp);
templateCtx.put("templateRootTemplate", templateRootTmp);
} else {
templateRoot = UtilMisc.makeMapWritable(templateRootTemplate);
}
templateRoot.put("context", templateCtx);
if (Debug.verboseOn()) {
for (Object ky : templateCtx.keySet()) {
Object val = templateCtx.get(ky);
Debug.logVerbose("context key: " + ky + " val: " + val, module);
}
}
String mimeTypeId = (String)templateCtx.get("mimeTypeId");
Locale locale = null;
try {
//if (Debug.infoOn()) Debug.logInfo("in Edit(0), before calling renderContentAsTextCache, wrapTemplateId: ." + wrapTemplateId , module);
ContentWorker.renderContentAsText(dispatcher, delegator, wrapTemplateId, out, templateRoot, locale, mimeTypeId, null, null, true);
//if (Debug.infoOn()) Debug.logInfo("in Edit(0), after calling renderContentAsTextCache, wrapTemplateId: ." + wrapTemplateId , module);
} catch (IOException e) {
Debug.logError(e, "Error rendering content" + e.getMessage(), module);
throw new IOException("Error rendering content" + e.toString());
} catch (GeneralException e2) {
Debug.logError(e2, "Error rendering content" + e2.getMessage(), module);
throw new IOException("Error rendering content" + e2.toString());
}
} else {
out.write(wrappedContent);
}
}
};
}
}
@@ -0,0 +1,228 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.LocalDispatcher;
import freemarker.core.Environment;
import freemarker.template.TemplateTransformModel;
/**
* EditRenderSubContentTransform - Freemarker Transform for URLs (links)
*
* This is an interactive FreeMarker tranform that allows the user to modify the contents that are placed within it.
*/
public class EditRenderSubContentTransform implements TemplateTransformModel {
public static final String module = EditRenderSubContentTransform.class.getName();
/**
* @deprecated use FreeMarkerWorker.getWrappedObject()
* A wrapper for the FreeMarkerWorker version.
*/
@Deprecated
public static Object getWrappedObject(String varName, Environment env) {
return FreeMarkerWorker.getWrappedObject(varName, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, ? extends Object> args, String key, Environment env) {
return FreeMarkerWorker.getArg(args, key, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, ? extends Object> args, String key, Map<String, ? extends Object> ctx) {
return FreeMarkerWorker.getArg(args, key, ctx);
}
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
Map<String, Object> ctx = FreeMarkerWorker.getWrappedObject("context", env);
final String editTemplate = FreeMarkerWorker.getArg(args, "editTemplate", ctx);
final String wrapTemplateId = FreeMarkerWorker.getArg(args, "wrapTemplateId", ctx);
final String mapKey = FreeMarkerWorker.getArg(args, "mapKey", ctx);
final String templateContentId = FreeMarkerWorker.getArg(args, "templateContentId", ctx);
final String subContentId = FreeMarkerWorker.getArg(args, "subContentId", ctx);
String subDataResourceTypeIdTemp = FreeMarkerWorker.getArg(args, "subDataResourceTypeId", ctx);
final String contentId = FreeMarkerWorker.getArg(args, "contentId", ctx);
final Locale locale = FreeMarkerWorker.getWrappedObject("locale", env);
String mimeTypeIdTemp = FreeMarkerWorker.getArg(args, "mimeTypeId", ctx);
final String rootDir = FreeMarkerWorker.getArg(args, "rootDir", ctx);
final String webSiteId = FreeMarkerWorker.getArg(args, "webSiteId", ctx);
final String https = FreeMarkerWorker.getArg(args, "https", ctx);
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
GenericValue subContentDataResourceViewTemp = FreeMarkerWorker.getWrappedObject("subContentDataResourceView", env);
//final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
ctx.put("mapKey", mapKey);
ctx.put("subDataResourceTypeIdTemp", subDataResourceTypeIdTemp);
ctx.put("contentId", contentId);
ctx.put("templateContentId", templateContentId);
ctx.put("locale", locale);
// This transform does not need information about the subContent until the
// close action, but any embedded RenderDataResourceTransformation will need it
// and since it cannot be passed back up from that transform, the subContent view
// is gotten here and made available to underlying transforms to save overall
// processing time.
GenericValue parentContent = null;
//ctx.put("userLogin", userLogin);
List<String> assocTypes = UtilMisc.toList("SUB_CONTENT");
Timestamp fromDate = UtilDateTime.nowTimestamp();
if (subContentDataResourceViewTemp == null) {
try {
subContentDataResourceViewTemp = ContentWorker.getSubContent(delegator, contentId, mapKey, subContentId, userLogin, assocTypes, fromDate);
} catch (IOException e) {
Debug.logError(e, "Error getting sub-content", module);
throw new RuntimeException(e.getMessage());
}
}
final GenericValue subContentDataResourceView = subContentDataResourceViewTemp;
String dataResourceIdTemp = null;
String subContentIdSubTemp = null;
if (subContentDataResourceView != null && subContentDataResourceView.get("contentId") != null) {
dataResourceIdTemp = (String) subContentDataResourceView.get("drDataResourceId");
subContentIdSubTemp = (String) subContentDataResourceView.get("contentId");
if (UtilValidate.isEmpty(subDataResourceTypeIdTemp)) {
subDataResourceTypeIdTemp = (String) subContentDataResourceView.get("drDataResourceTypeId");
}
if (UtilValidate.isEmpty(mimeTypeIdTemp)) {
mimeTypeIdTemp = (String) subContentDataResourceView.get("mimeTypeId");
if (UtilValidate.isEmpty(mimeTypeIdTemp) && UtilValidate.isNotEmpty(contentId)) { // will need these below
try {
parentContent = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
if (parentContent != null) {
mimeTypeIdTemp = (String) parentContent.get("mimeTypeId");
}
} catch (GenericEntityException e) {
throw new RuntimeException(e.getMessage());
}
}
}
ctx.put("subContentId", subContentIdSubTemp);
ctx.put("drDataResourceId", dataResourceIdTemp);
ctx.put("subContentDataResourceView", subContentDataResourceView);
ctx.put("mimeTypeId", mimeTypeIdTemp);
//request.setAttribute("drDataResourceId", subContentDataResourceView.get("drDataResourceId"));
} else {
ctx.put("subContentId", null);
ctx.put("drDataResourceId", null);
ctx.put("subContentDataResourceView", null);
ctx.put("mimeTypeId", null);
//request.setAttribute("drDataResourceId", null);
}
final String dataResourceId = dataResourceIdTemp;
final String subContentIdSub = subContentIdSubTemp;
//final GenericValue finalSubContentView = subContentDataResourceView;
//final GenericValue content = parentContent;
final Map<String, Object> templateContext = ctx;
final String mimeTypeId = mimeTypeIdTemp;
final String subDataResourceTypeId = subDataResourceTypeIdTemp;
return new Writer(out) {
@Override
public void write(char cbuf[], int off, int len) {
buf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
String wrappedFTL = buf.toString();
if (editTemplate != null && editTemplate.equalsIgnoreCase("true")) {
if (UtilValidate.isNotEmpty(wrapTemplateId)) {
templateContext.put("wrappedFTL", wrappedFTL);
//ServletContext servletContext = (ServletContext)request.getSession().getServletContext();
//String rootDir = servletContext.getRealPath("/");
templateContext.put("webSiteId", webSiteId);
templateContext.put("https", https);
templateContext.put("rootDir", rootDir);
Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
templateRoot.put("wrapDataResourceId", dataResourceId);
templateRoot.put("wrapDataResourceTypeId", subDataResourceTypeId);
templateRoot.put("wrapContentIdTo", contentId);
templateRoot.put("wrapSubContentId", subContentIdSub);
templateRoot.put("wrapMimeTypeId", mimeTypeId);
templateRoot.put("wrapMapKey", mapKey);
templateRoot.put("context", templateContext);
try {
ContentWorker.renderContentAsText(dispatcher, delegator, wrapTemplateId, out, templateRoot, locale, mimeTypeId, null, null, false);
} catch (IOException e) {
Debug.logError(e, "Error rendering content" + e.getMessage(), module);
throw new IOException("Error rendering content" + e.toString());
} catch (GeneralException e2) {
Debug.logError(e2, "Error rendering content" + e2.getMessage(), module);
throw new IOException("Error rendering content" + e2.toString());
}
FreeMarkerWorker.getWrappedObject("context", env);
templateContext.put("contentId", contentId);
templateContext.put("locale", locale);
templateContext.put("mapKey", null);
templateContext.put("subContentId", null);
templateContext.put("templateContentId", null);
templateContext.put("subDataResourceTypeId", null);
templateContext.put("mimeTypeId", null);
templateContext.put("wrappedFTL", null);
}
} else {
out.write(wrappedFTL);
}
}
};
}
}
@@ -0,0 +1,183 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.webapp.ftl.LoopWriter;
import freemarker.core.Environment;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;
import freemarker.template.TransformControl;
/**
* InjectNodeTrailCsvTransform - Freemarker Transform for URLs (links)
*/
public class InjectNodeTrailCsvTransform implements TemplateTransformModel {
public static final String module = InjectNodeTrailCsvTransform.class.getName();
public static final String [] saveKeyNames = {"nodeTrailCsv","globalNodeTrail", "nodeTrail"};
public static final String [] removeKeyNames = {"nodeTrailCsv"};
/**
* @deprecated use FreeMarkerWorker.getWrappedObject()
* A wrapper for the FreeMarkerWorker version.
*/
@Deprecated
public static Object getWrappedObject(String varName, Environment env) {
return FreeMarkerWorker.getWrappedObject(varName, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, ? extends Object> args, String key, Environment env) {
return FreeMarkerWorker.getArg(args, key, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, ? extends Object> args, String key, Map<String, ? extends Object> ctx) {
return FreeMarkerWorker.getArg(args, key, ctx);
}
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
final Map<String, Object> templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
//FreeMarkerWorker.convertContext(templateCtx);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
//final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
FreeMarkerWorker.getSiteParameters(request, templateCtx);
FreeMarkerWorker.overrideWithArgs(templateCtx, args);
return new LoopWriter(out) {
final String passedCsv = (String)templateCtx.get("nodeTrailCsv");
@Override
public void write(char cbuf[], int off, int len) {
buf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public int onStart() throws TemplateModelException, IOException {
String csvTrail = null;
List<Map<String, ? extends Object>> trail = UtilGenerics.checkList(templateCtx.get("globalNodeTrail"));
if (Debug.infoOn()) Debug.logInfo("in InjectNodeTrailCsv(0), trail:"+trail,module);
// This will build a nodeTrail if none exists
// Maybe only contentId or subContentId are passed in
//GenericValue currentValue = getCurrentContent(delegator, trail, userLogin, templateCtx, nullThruDatesOnly, contentAssocPredicateId);
String redo = (String)templateCtx.get("redo");
if (UtilValidate.isEmpty(trail) || (redo != null && redo.equalsIgnoreCase("true"))) {
// String thisContentId = null;
String subContentId = (String)templateCtx.get("subContentId");
if (Debug.infoOn()) Debug.logInfo("in InjectNodeTrailCsv(0), subContentId:"+subContentId,module);
String contentId = (String)templateCtx.get("contentId");
if (Debug.infoOn()) Debug.logInfo("in InjectNodeTrailCsv(0), contentId:"+contentId,module);
String contentAssocTypeId = (String)templateCtx.get("contentAssocTypeId");
if (Debug.infoOn()) Debug.logInfo("in InjectNodeTrailCsv(0), contentAssocTypeId:"+contentAssocTypeId,module);
try {
if (UtilValidate.isNotEmpty(subContentId)) {
csvTrail = ContentWorker.getContentAncestryNodeTrailCsv(delegator, subContentId, contentAssocTypeId, "to");
if (UtilValidate.isNotEmpty(csvTrail))
csvTrail += ",";
csvTrail += subContentId;
} else if (UtilValidate.isNotEmpty(contentId)) {
csvTrail = ContentWorker.getContentAncestryNodeTrailCsv(delegator, contentId, contentAssocTypeId, "to");
if (UtilValidate.isNotEmpty(csvTrail))
csvTrail += ",";
csvTrail += contentId;
}
} catch (GenericEntityException e) {
throw new RuntimeException("Error getting current content. " + e.toString());
}
if (Debug.infoOn()) Debug.logInfo("in InjectNodeTrailCsv(0), csvTrail:"+csvTrail,module);
} else {
// Build nodeTrail if one does not exist
//if (Debug.infoOn()) Debug.logInfo("in InjectNodeTrailCsv, trail:"+trail,module);
//if (Debug.infoOn()) Debug.logInfo("in InjectNodeTrailCsv, passedCsv:"+passedCsv,module);
if (UtilValidate.isNotEmpty(passedCsv)) {
csvTrail = passedCsv;
int lastComma = passedCsv.lastIndexOf(",");
String lastPassedContentId = null;
if (lastComma >= 0) {
lastPassedContentId = passedCsv.substring(lastComma + 1);
} else {
lastPassedContentId = passedCsv;
}
if (UtilValidate.isNotEmpty(lastPassedContentId)) {
if (UtilValidate.isNotEmpty(trail)) {
Map<String, ? extends Object> nd = trail.get(0);
String firstTrailContentId = (String)nd.get("contentId");
if (UtilValidate.isNotEmpty(firstTrailContentId)
&& UtilValidate.isNotEmpty(lastPassedContentId)
&& firstTrailContentId.equals(lastPassedContentId)) {
csvTrail += "," + ContentWorker.nodeTrailToCsv(trail.subList(1, trail.size()));
} else {
csvTrail += "," + ContentWorker.nodeTrailToCsv(trail);
}
}
}
} else {
csvTrail = ContentWorker.nodeTrailToCsv(trail);
}
}
//if (Debug.infoOn()) Debug.logInfo("in InjectNodeTrailCsv, csvTrail:"+csvTrail,module);
templateCtx.put("nodeTrailCsv", csvTrail);
return TransformControl.EVALUATE_BODY;
}
@Override
public void close() throws IOException {
templateCtx.put("nodeTrailCsv", passedCsv);
String wrappedContent = buf.toString();
out.write(wrappedContent);
}
};
}
}
@@ -0,0 +1,335 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.StringUtil;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentServicesComplex;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.minilang.MiniLangException;
import org.ofbiz.webapp.ftl.LoopWriter;
import freemarker.core.Environment;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;
import freemarker.template.TransformControl;
/**
* LimitedSubContentCacheTransform - Freemarker Transform for URLs (links)
*/
public class LimitedSubContentCacheTransform implements TemplateTransformModel {
public static final String module = LimitedSubContentCacheTransform.class.getName();
public static final String [] upSaveKeyNames = {"globalNodeTrail"};
public static final String [] saveKeyNames = {"contentId", "subContentId", "entityList", "entityIndex", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "entityList", "viewSize", "viewIndex", "highIndex", "lowIndex", "listSize", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail", "outputIndex"};
/**
* @deprecated use FreeMarkerWorker.getWrappedObject()
* A wrapper for the FreeMarkerWorker version.
*/
@Deprecated
public static Object getWrappedObject(String varName, Environment env) {
return FreeMarkerWorker.getWrappedObject(varName, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, ? extends Object> args, String key, Environment env) {
return FreeMarkerWorker.getArg(args, key, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, ? extends Object> args, String key, Map<String, ? extends Object> ctx) {
return FreeMarkerWorker.getArg(args, key, ctx);
}
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
//Profiler.begin("Limited");
final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
final Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
FreeMarkerWorker.getSiteParameters(request, templateRoot);
final Map<String, Object> savedValuesUp = new HashMap<String, Object>();
FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
final Map<String, Object> savedValues = new HashMap<String, Object>();
FreeMarkerWorker.overrideWithArgs(templateRoot, args);
String contentAssocTypeId = (String) templateRoot.get("contentAssocTypeId");
if (UtilValidate.isEmpty(contentAssocTypeId)) {
contentAssocTypeId = "SUB_CONTENT";
templateRoot.put("contentAssocTypeId ", contentAssocTypeId);
}
final Map<String, GenericValue> pickedEntityIds = new HashMap<String, GenericValue>();
List<String> assocTypes = StringUtil.split(contentAssocTypeId, "|");
String contentPurposeTypeId = (String) templateRoot.get("contentPurposeTypeId");
List<String> purposeTypes = StringUtil.split(contentPurposeTypeId, "|");
templateRoot.put("purposeTypes", purposeTypes);
Locale locale = (Locale) templateRoot.get("locale");
if (locale == null) {
locale = Locale.getDefault();
templateRoot.put("locale", locale);
}
Map<String, Object> whenMap = new HashMap<String, Object>();
whenMap.put("followWhen", templateRoot.get("followWhen"));
whenMap.put("pickWhen", templateRoot.get("pickWhen"));
whenMap.put("returnBeforePickWhen", templateRoot.get("returnBeforePickWhen"));
whenMap.put("returnAfterPickWhen", templateRoot.get("returnAfterPickWhen"));
templateRoot.put("whenMap", whenMap);
String fromDateStr = (String) templateRoot.get("fromDateStr");
Timestamp fromDate = null;
if (UtilValidate.isNotEmpty(fromDateStr)) {
fromDate = UtilDateTime.toTimestamp(fromDateStr);
}
if (fromDate == null) {
fromDate = UtilDateTime.nowTimestamp();
}
String limitSize = (String) templateRoot.get("limitSize");
final int returnLimit = Integer.parseInt(limitSize);
// limitMode will be "random" to begin with
// String limitMode = (String) templateRoot.get("limitMode");
// final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
// List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
// String strNullThruDatesOnly = (String) templateRoot.get("nullThruDatesOnly");
// Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && strNullThruDatesOnly.equalsIgnoreCase("true")) ? Boolean.TRUE : Boolean.FALSE;
String orderBy = (String) templateRoot.get("orderBy");
// NOTE this was looking for subContentId, but that doesn't make ANY sense, so changed to contentId
String contentId = (String) templateRoot.get("contentId");
templateRoot.put("contentId", null);
templateRoot.put("subContentId", null);
// final String contentIdTo = contentId;
Map<String, Object> results = null;
//if (Debug.infoOn()) Debug.logInfo("in LimitedSubContentCache(0), assocTypes ." + assocTypes, module);
String contentAssocPredicateId = (String) templateRoot.get("contentAssocPredicateId");
try {
results = ContentServicesComplex.getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, null, "From", fromDate, null, assocTypes, null, Boolean.TRUE, contentAssocPredicateId, orderBy);
} catch (MiniLangException e) {
throw new RuntimeException(e.getMessage(), e);
} catch (GenericEntityException e) {
throw new RuntimeException(e.getMessage(), e);
}
List<GenericValue> longList = UtilGenerics.checkList(results.get("entityList"));
templateRoot.put("entityList", longList);
//if (Debug.infoOn()) Debug.logInfo("in limited, longList:" + longList , "");
return new LoopWriter(out) {
@Override
public void write(char cbuf[], int off, int len) {
buf.append(cbuf, off, len);
//StringBuilder ctxBuf = (StringBuilder) templateRoot.get("buf");
//ctxBuf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public int onStart() throws TemplateModelException, IOException {
// List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
// String trailCsv = ContentWorker.nodeTrailToCsv(globalNodeTrail);
boolean inProgress = false;
//if (Debug.infoOn()) Debug.logInfo("in limited, returnLimit:" + returnLimit , "");
//if (Debug.infoOn()) Debug.logInfo("in limited, pickedEntityIds:" + pickedEntityIds , "");
if (pickedEntityIds.size() < returnLimit) {
inProgress = getNextMatchingEntity(templateRoot, delegator, env);
}
FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
if (inProgress) {
return TransformControl.EVALUATE_BODY;
} else {
return TransformControl.SKIP_BODY;
}
}
@Override
public int afterBody() throws TemplateModelException, IOException {
FreeMarkerWorker.reloadValues(templateRoot, savedValues, env);
List<Map<String, ? extends Object>> list = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
List<Map<String, ? extends Object>> subList = list.subList(0, list.size() - 1);
templateRoot.put("globalNodeTrail", subList);
env.setVariable("globalNodeTrail", FreeMarkerWorker.autoWrap(subList, env));
//if (Debug.infoOn()) Debug.logInfo("highIndex(2):" + highIndexInteger , "");
//if (Debug.infoOn()) Debug.logInfo("in limited, returnLimit(2):" + returnLimit , "");
//if (Debug.verboseOn()) Debug.logVerbose("in limited, pickedEntityIds(2):" + pickedEntityIds , "");
boolean inProgress = false;
if (pickedEntityIds.size() < returnLimit) {
inProgress = getNextMatchingEntity(templateRoot, delegator, env);
}
FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
if (inProgress) {
return TransformControl.REPEAT_EVALUATION;
} else {
return TransformControl.END_EVALUATION;
}
}
@Override
public void close() throws IOException {
FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
String wrappedContent = buf.toString();
out.write(wrappedContent);
//try {
//Profiler.end("Limited");
//FileOutputStream fw = new FileOutputStream(FileUtil.getFile("/usr/local/agi/ofbiz/hot-deploy/sfmp/misc/profile.data"));
//Profiler.print(fw);
//fw.close();
//} catch (IOException e) {
//Debug.logError("[PROFILER] " + e.getMessage(),"");
//}
}
public boolean prepCtx(Delegator delegator, Map<String, Object> ctx, Environment env, GenericValue view) throws GeneralException {
// String dataResourceId = (String) view.get("drDataResourceId");
String subContentIdSub = (String) view.get("contentId");
// This order is taken so that the dataResourceType can be overridden in the transform arguments.
String subDataResourceTypeId = (String) ctx.get("subDataResourceTypeId");
if (UtilValidate.isEmpty(subDataResourceTypeId)) {
subDataResourceTypeId = (String) view.get("drDataResourceTypeId");
// TODO: If this value is still empty then it is probably necessary to get a value from
// the parent context. But it will already have one and it is the same context that is
// being passed.
}
String mimeTypeId = ContentWorker.getMimeTypeId(delegator, view, ctx);
Map<String, Object> trailNode = ContentWorker.makeNode(view);
Map<String, Object> whenMap = UtilGenerics.checkMap(ctx.get("whenMap"));
Locale locale = (Locale) ctx.get("locale");
if (locale == null) {
locale = Locale.getDefault();
}
GenericValue assocContent = null;
ContentWorker.checkConditions(delegator, trailNode, assocContent, whenMap);
Boolean isReturnBeforeObj = (Boolean) trailNode.get("isReturnBefore");
// Boolean isReturnAfterObj = (Boolean) trailNode.get("isReturnAfter");
Boolean isPickObj = (Boolean) trailNode.get("isPick");
Boolean isFollowObj = (Boolean) trailNode.get("isFollow");
//if (Debug.infoOn()) Debug.logInfo("in LimitedSubContentCache, isReturnBeforeObj" + isReturnBeforeObj + " isPickObj:" + isPickObj + " isFollowObj:" + isFollowObj + " isReturnAfterObj:" + isReturnAfterObj, module);
if ((isReturnBeforeObj == null || !isReturnBeforeObj.booleanValue()) && ((isPickObj != null &&
isPickObj.booleanValue()) || (isFollowObj != null && isFollowObj.booleanValue()))) {
List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(ctx.get("globalNodeTrail"));
if (globalNodeTrail == null) {
globalNodeTrail = new LinkedList<Map<String,? extends Object>>();
}
globalNodeTrail.add(trailNode);
ctx.put("globalNodeTrail", globalNodeTrail);
String csvTrail = ContentWorker.nodeTrailToCsv(globalNodeTrail);
ctx.put("nodeTrailCsv", csvTrail);
//if (Debug.infoOn()) Debug.logInfo("prepCtx, csvTrail(2):" + csvTrail, "");
int indentSz = globalNodeTrail.size();
ctx.put("indent", Integer.valueOf(indentSz));
ctx.put("subDataResourceTypeId", subDataResourceTypeId);
ctx.put("mimeTypeId", mimeTypeId);
ctx.put("subContentId", subContentIdSub);
ctx.put("content", view);
env.setVariable("subDataResourceTypeId", FreeMarkerWorker.autoWrap(subDataResourceTypeId, env));
env.setVariable("indent", FreeMarkerWorker.autoWrap(Integer.valueOf(indentSz), env));
env.setVariable("nodeTrailCsv", FreeMarkerWorker.autoWrap(csvTrail, env));
env.setVariable("globalNodeTrail", FreeMarkerWorker.autoWrap(globalNodeTrail, env));
env.setVariable("content", FreeMarkerWorker.autoWrap(view, env));
env.setVariable("mimeTypeId", FreeMarkerWorker.autoWrap(mimeTypeId, env));
env.setVariable("subContentId", FreeMarkerWorker.autoWrap(subContentIdSub, env));
return true;
} else {
return false;
}
}
public GenericValue getRandomEntity() {
GenericValue pickEntity = null;
List<GenericValue> lst = UtilGenerics.checkList(templateRoot.get("entityList"));
if (Debug.verboseOn()) Debug.logVerbose("in limited, lst:" + lst, "");
while (pickEntity == null && lst.size() > 0) {
double randomValue = Math.random();
//if (Debug.infoOn()) Debug.logInfo("in limited, randomValue:" + randomValue , "");
int idx = (int) (lst.size() * randomValue);
//if (Debug.infoOn()) Debug.logInfo("in limited, idx:" + idx , "");
pickEntity = lst.get(idx);
String pickEntityId = pickEntity.getString("contentId");
if (pickedEntityIds.get(pickEntityId) == null) {
pickedEntityIds.put(pickEntityId, pickEntity);
lst.remove(idx);
} else {
pickEntity = null;
}
}
return pickEntity;
}
public boolean getNextMatchingEntity(Map<String, Object> templateRoot, Delegator delegator, Environment env) throws IOException {
boolean matchFound = false;
GenericValue pickEntity = getRandomEntity();
while (pickEntity != null && !matchFound) {
try {
matchFound = prepCtx(delegator, templateRoot, env, pickEntity);
} catch (GeneralException e) {
throw new IOException(e.getMessage());
}
if (!matchFound)
pickEntity = getRandomEntity();
}
return matchFound;
}
};
}
}
@@ -0,0 +1,262 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentServicesComplex;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.webapp.ftl.LoopWriter;
import freemarker.core.Environment;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;
import freemarker.template.TransformControl;
/**
* LoopSubContentTransform - Freemarker Transform for URLs (links)
*/
public class LoopSubContentTransform implements TemplateTransformModel {
public static final String module = LoopSubContentTransform.class.getName();
public static final String[] saveKeyNames = {"contentId", "subContentId", "mimeType", "subContentDataResourceView", "wrapTemplateId", "contentTemplateId"};
public static final String[] removeKeyNames = {"wrapTemplateId", "entityList", "entityIndex", "textData", "dataResourceId","drDataResourceId", "subContentIdSub", "parentContent", "wrappedFTL"};
/**
* @deprecated use FreeMarkerWorker.getWrappedObject()
* A wrapper for the FreeMarkerWorker version.
*/
@Deprecated
public static Object getWrappedObject(String varName, Environment env) {
return FreeMarkerWorker.getWrappedObject(varName, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, Object> args, String key, Environment env) {
return FreeMarkerWorker.getArg(args, key, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, Object> args, String key, Map<String, Object> ctx) {
return FreeMarkerWorker.getArg(args, key, ctx);
}
public static boolean prepCtx(Delegator delegator, Map<String, Object> ctx) {
List<GenericValue> lst = UtilGenerics.checkList(ctx.get("entityList"));
Integer idx = (Integer) ctx.get("entityIndex");
if (idx == null) idx = Integer.valueOf(0);
int i = idx.intValue();
if (UtilValidate.isEmpty(lst)) {
return false;
} else if (i >= lst.size()) {
return false;
}
GenericValue subContentDataResourceView = lst.get(i);
ctx.put("subContentDataResourceView", subContentDataResourceView);
GenericValue electronicText = null;
try {
electronicText = subContentDataResourceView.getRelatedOne("ElectronicText", false);
} catch (GenericEntityException e) {
throw new RuntimeException(e.getMessage());
}
String dataResourceId = (String) subContentDataResourceView.get("drDataResourceId");
String subContentIdSub = (String) subContentDataResourceView.get("contentId"); // in ContentAssocDataResourceViewTo
// This order is taken so that the dataResourceType can be overridden in the transform arguments.
String subDataResourceTypeId = (String) ctx.get("subDataResourceTypeId");
if (UtilValidate.isEmpty(subDataResourceTypeId)) {
subDataResourceTypeId = (String) subContentDataResourceView.get("drDataResourceTypeId");
// TODO: If this value is still empty then it is probably necessary to get a value from
// the parent context. But it will already have one and it is the same context that is
// being passed.
}
// This order is taken so that the mimeType can be overridden in the transform arguments.
String mimeTypeId = (String) ctx.get("mimeTypeId");
if (UtilValidate.isEmpty(mimeTypeId)) {
mimeTypeId = (String) subContentDataResourceView.get("mimeTypeId");
String parentContentId = (String)ctx.get("contentId");
if (UtilValidate.isEmpty(mimeTypeId) && UtilValidate.isNotEmpty(parentContentId)) { // will need these below
try {
GenericValue parentContent = EntityQuery.use(delegator).from("Content").where("contentId", parentContentId).queryOne();
if (parentContent != null) {
mimeTypeId = (String) parentContent.get("mimeTypeId");
ctx.put("parentContent", parentContent);
}
} catch (GenericEntityException e) {
throw new RuntimeException(e.getMessage());
}
}
}
// This is what the FM template will see.
ctx.put("subContentDataResourceView", subContentDataResourceView);
if (electronicText != null) {
ctx.put("textData", electronicText.get("textData"));
} else {
ctx.put("textData", null);
}
ctx.put("content", subContentDataResourceView);
ctx.put("entityIndex", Integer.valueOf(i + 1));
ctx.put("subContentId", subContentIdSub);
ctx.put("drDataResourceId", dataResourceId);
ctx.put("mimeTypeId", mimeTypeId);
ctx.put("dataResourceId", dataResourceId);
ctx.put("subContentIdSub", subContentIdSub);
ctx.put("subDataResourceTypeId", subDataResourceTypeId);
return true;
}
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
final Map<String, Object> templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final Map<String, Object> savedValues = FreeMarkerWorker.saveValues(templateCtx, saveKeyNames);
FreeMarkerWorker.overrideWithArgs(templateCtx, args);
String contentAssocTypeId = (String) templateCtx.get("contentAssocTypeId");
if (UtilValidate.isEmpty(contentAssocTypeId)) {
contentAssocTypeId = "SUB_CONTENT";
templateCtx.put("contentAssocTypeId ", contentAssocTypeId);
}
List<String> assocTypes = UtilMisc.toList(contentAssocTypeId);
templateCtx.put("assocTypes", assocTypes);
Locale locale = (Locale) templateCtx.get("locale");
if (locale == null) {
locale = Locale.getDefault();
templateCtx.put("locale", locale);
}
String fromDateStr = (String) templateCtx.get("fromDateStr");
Timestamp fromDate = null;
if (UtilValidate.isNotEmpty(fromDateStr)) {
fromDate = UtilDateTime.toTimestamp(fromDateStr);
}
if (fromDate == null) fromDate = UtilDateTime.nowTimestamp();
String thisContentId = (String) templateCtx.get("contentId");
//DEJ20080730 Should always use contentId, not subContentId since we're searching for that and it is confusing
//if (UtilValidate.isEmpty(thisContentId)) thisContentId = (String)templateCtx.get("subContentId");
String thisMapKey = (String)templateCtx.get("mapKey");
//GenericValue subContentDataResourceView = null;
Map<String, Object> results = ContentServicesComplex.getAssocAndContentAndDataResourceMethod(delegator, thisContentId, thisMapKey, null, fromDate, null, null, null, assocTypes, null);
List<GenericValue> entityList = UtilGenerics.checkList(results.get("entityList"));
templateCtx.put("entityList", entityList);
return new LoopWriter(out) {
@Override
public void write(char cbuf[], int off, int len) {
buf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public int onStart() throws TemplateModelException, IOException {
templateCtx.put("entityIndex", Integer.valueOf(0));
boolean inProgress = prepCtx(delegator, templateCtx);
if (inProgress) {
return TransformControl.EVALUATE_BODY;
} else {
return TransformControl.SKIP_BODY;
}
}
@Override
public int afterBody() throws TemplateModelException, IOException {
boolean inProgress = prepCtx(delegator, templateCtx);
if (inProgress) {
return TransformControl.REPEAT_EVALUATION;
} else {
return TransformControl.END_EVALUATION;
}
}
@Override
public void close() throws IOException {
String wrappedFTL = buf.toString();
String encloseWrappedText = (String) templateCtx.get("encloseWrappedText");
if (UtilValidate.isEmpty(encloseWrappedText) || encloseWrappedText.equalsIgnoreCase("false")) {
out.write(wrappedFTL);
wrappedFTL = ""; // So it won't get written again below.
}
String wrapTemplateId = (String)templateCtx.get("wrapTemplateId");
if (UtilValidate.isNotEmpty(wrapTemplateId)) {
templateCtx.put("wrappedFTL", wrappedFTL);
Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
templateRoot.put("wrapDataResourceTypeId", templateCtx.get("subDataResourceTypeId"));
templateRoot.put("wrapContentIdTo", templateCtx.get("contentId"));
templateRoot.put("wrapMimeTypeId", templateCtx.get("mimeTypeId"));
templateRoot.put("context", templateCtx);
Locale locale = (Locale) templateCtx.get("locale");
if (locale == null) locale = Locale.getDefault();
String mimeTypeId = (String) templateCtx.get("mimeTypeId");
try {
ContentWorker.renderContentAsText(dispatcher, delegator, wrapTemplateId, out, templateRoot, locale, mimeTypeId, null, null, true);
} catch (GeneralException e) {
Debug.logError(e, "Error rendering content", module);
throw new IOException("Error rendering content" + e.toString());
}
} else {
if (UtilValidate.isNotEmpty(wrappedFTL)) {
out.write(wrappedFTL);
}
}
FreeMarkerWorker.removeValues(templateCtx, removeKeyNames);
FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
}
};
}
}
@@ -0,0 +1,99 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.content.content.ContentUrlFilter;
import freemarker.core.Environment;
import freemarker.ext.beans.BeanModel;
import freemarker.ext.beans.NumberModel;
import freemarker.ext.beans.StringModel;
import freemarker.template.SimpleNumber;
import freemarker.template.SimpleScalar;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;
public class OfbizContentAltUrlTransforms implements TemplateTransformModel {
public final static String module = OfbizContentAltUrlTransforms.class.getName();
public String getStringArg(Map args, String key) {
Object o = args.get(key);
if (o instanceof SimpleScalar) {
return ((SimpleScalar) o).getAsString();
} else if (o instanceof StringModel) {
return ((StringModel) o).getAsString();
} else if (o instanceof SimpleNumber) {
return ((SimpleNumber) o).getAsNumber().toString();
} else if (o instanceof NumberModel) {
return ((NumberModel) o).getAsNumber().toString();
}
return null;
}
@Override
public Writer getWriter(final Writer out, final Map args)
throws TemplateModelException, IOException {
final StringBuilder buf = new StringBuilder();
return new Writer(out) {
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
buf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
try {
Environment env = Environment.getCurrentEnvironment();
BeanModel req = (BeanModel) env.getVariable("request");
BeanModel res = (BeanModel) env.getVariable("response");
if (req != null) {
String contentId = getStringArg(args, "contentId");
String viewContent = getStringArg(args, "viewContent");
HttpServletRequest request = (HttpServletRequest) req.getWrappedObject();
HttpServletResponse response = null;
if (res != null) {
response = (HttpServletResponse) res.getWrappedObject();
}
String url = "";
if (UtilValidate.isNotEmpty(contentId)) {
url = ContentUrlFilter.makeContentAltUrl(request, response, contentId, viewContent);
}
out.write(url);
}
} catch (TemplateModelException e) {
throw new IOException(e.getMessage());
}
}
};
}
}
@@ -0,0 +1,140 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.collections.MapStack;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.service.LocalDispatcher;
import freemarker.core.Environment;
import freemarker.template.TemplateTransformModel;
/**
* RenderContentAndSubContent - Freemarker Transform for Content rendering
* This transform cannot be called recursively (at this time).
*/
public class RenderContentAndSubContent implements TemplateTransformModel {
public static final String module = RenderContentAndSubContent.class.getName();
// public static final String [] upSaveKeyNames = {"globalNodeTrail"};
// public static final String [] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final Environment env = Environment.getCurrentEnvironment();
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
// final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env);
final Map<String, Object> envMap = FreeMarkerWorker.createEnvironmentMap(env);
final MapStack<String> templateRoot = MapStack.create();
((MapStack)templateRoot).push(envMap);
if (Debug.verboseOn()) Debug.logVerbose("in RenderContentAndSubContent, contentId(0):" + templateRoot.get("contentId"), module);
FreeMarkerWorker.getSiteParameters(request, templateRoot);
// final Map savedValuesUp = new HashMap<String, Object>();
// FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
FreeMarkerWorker.overrideWithArgs(templateRoot, args);
// final Map<String, Object> savedValues = new HashMap<String, Object>();
return new Writer(out) {
@Override
public void write(char cbuf[], int off, int len) {
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
renderSubContent();
//if (Debug.verboseOn()) Debug.logVerbose("in Render(2), globalNodeTrail ." + getWrapped(env, "globalNodeTrail") , module);
}
public void renderSubContent() throws IOException {
String mimeTypeId = (String) templateRoot.get("mimeTypeId");
Object localeObject = templateRoot.get("locale");
Locale locale = null;
if (localeObject == null) {
locale = UtilHttp.getLocale(request);
} else {
locale = UtilMisc.ensureLocale(localeObject);
}
if (Debug.verboseOn()) Debug.logVerbose("in RenderContentAndSubContent, contentId(2):" + templateRoot.get("contentId"), module);
if (Debug.verboseOn()) Debug.logVerbose("in RenderContentAndSubContent, subContentId(2):" + templateRoot.get("subContentId"), module);
//if (thisView != null) {
try {
String contentId = (String)templateRoot.get("contentId");
String mapKey = (String)templateRoot.get("mapKey");
String contentAssocTypeId = (String)templateRoot.get("contentAssocTypeId");
if (UtilValidate.isNotEmpty(mapKey) || UtilValidate.isNotEmpty(contentAssocTypeId)) {
String txt = ContentWorker.renderSubContentAsText(dispatcher, delegator, contentId, mapKey, templateRoot, locale, mimeTypeId, true);
//String txt = ContentWorker.renderSubContentAsTextCache(delegator, thisContentId, thisMapKey, null, templateRoot, locale, mimeTypeId, null, fromDate);
// if ("true".equals(xmlEscape)) {
// txt = UtilFormatOut.encodeXmlValue(txt);
// }
out.write(txt);
// if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, after renderContentAsTextCache:", module);
// List assocList = null;
// if (UtilValidate.isNotEmpty(contentAssocTypeId)) {
// assocList = UtilMisc.toList(contentAssocTypeId);
// }
// GenericValue content = ContentWorker.getSubContent(delegator, contentId, mapKey, null, null, assocList, null);
// if (content != null) {
// contentId = content.getString("contentId");
// } else {
// contentId = null;
// }
} else if (contentId != null) {
ContentWorker.renderContentAsText(dispatcher, delegator, contentId, out, templateRoot, locale, mimeTypeId, null, null, true);
// ((MapStack)templateRoot).pop();
}
//FreeMarkerWorker.reloadValues(templateRoot, savedValues, env);
//FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
} catch (GeneralException e) {
String errMsg = "Error rendering thisContentId:" + (String)templateRoot.get("contentId") + " msg:" + e.toString();
Debug.logError(e, errMsg, module);
// just log a message and don't return anything: throw new IOException();
}
}
};
}
}
@@ -0,0 +1,260 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilFormatOut;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.webapp.control.RequestHandler;
import freemarker.core.Environment;
import freemarker.template.TemplateTransformModel;
/**
* RenderContentAsText - Freemarker Transform for Content rendering
* This transform cannot be called recursively (at this time).
*/
public class RenderContentAsText implements TemplateTransformModel {
public static final String module = RenderContentAsText.class.getName();
public static final String [] upSaveKeyNames = {"globalNodeTrail"};
public static final String [] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final Environment env = Environment.getCurrentEnvironment();
//final Map templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
//final Map templateCtx = new HashMap<String, Object>();
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env);
final Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
if (Debug.verboseOn()) {
Debug.logVerbose("in RenderSubContent, contentId(0):" + templateRoot.get("contentId"), module);
}
FreeMarkerWorker.getSiteParameters(request, templateRoot);
final Map<String, Object> savedValuesUp = new HashMap<String, Object>();
FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
FreeMarkerWorker.overrideWithArgs(templateRoot, args);
if (Debug.verboseOn()) {
Debug.logVerbose("in RenderSubContent, contentId(2):" + templateRoot.get("contentId"), module);
}
// not used yet: final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
// not used yet: List trail = (List)templateRoot.get("globalNodeTrail");
//if (Debug.infoOn()) Debug.logInfo("in Render(0), globalNodeTrail ." + trail , module);
// not used yet: String contentAssocPredicateId = (String)templateRoot.get("contentAssocPredicateId");
// not used yet: String strNullThruDatesOnly = (String)templateRoot.get("nullThruDatesOnly");
// not used yet: Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && strNullThruDatesOnly.equalsIgnoreCase("true")) ? Boolean.TRUE :Boolean.FALSE;
final String thisContentId = (String)templateRoot.get("contentId");
final String xmlEscape = (String)templateRoot.get("xmlEscape");
final boolean directAssocMode = UtilValidate.isNotEmpty(thisContentId) ? true : false;
if (Debug.verboseOn()) {
Debug.logVerbose("in Render(0), directAssocMode ." + directAssocMode , module);
}
/*
if (Debug.infoOn()) Debug.logInfo("in Render(0), thisSubContentId ." + thisSubContentId , module);
String thisSubContentId = (String)templateRoot.get("subContentId");
GenericValue val = null;
try {
val = FreeMarkerWorker.getCurrentContent(delegator, trail, userLogin, templateRoot, nullThruDatesOnly, contentAssocPredicateId);
} catch (GeneralException e) {
throw new RuntimeException("Error getting current content. " + e.toString());
}
final GenericValue view = val;
String dataResourceId = null;
String subContentIdSub = null;
if (view != null) {
try {
dataResourceId = (String) view.get("drDataResourceId");
} catch (Exception e) {
dataResourceId = (String) view.get("dataResourceId");
}
subContentIdSub = (String) view.get("contentId");
}
// This order is taken so that the dataResourceType can be overridden in the transform arguments.
String subDataResourceTypeId = (String)templateRoot.get("subDataResourceTypeId");
if (UtilValidate.isEmpty(subDataResourceTypeId)) {
try {
subDataResourceTypeId = (String) view.get("drDataResourceTypeId");
} catch (Exception e) {
// view may be "Content"
}
// TODO: If this value is still empty then it is probably necessary to get a value from
// the parent context. But it will already have one and it is the same context that is
// being passed.
}
String mimeTypeId = FreeMarkerWorker.getMimeTypeId(delegator, view, templateRoot);
templateRoot.put("drDataResourceId", dataResourceId);
templateRoot.put("mimeTypeId", mimeTypeId);
templateRoot.put("dataResourceId", dataResourceId);
templateRoot.put("subContentId", subContentIdSub);
templateRoot.put("subDataResourceTypeId", subDataResourceTypeId);
*/
final Map<String, Object> savedValues = new HashMap<String, Object>();
return new Writer(out) {
@Override
public void write(char cbuf[], int off, int len) {
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
if (Debug.verboseOn()) {
Debug.logVerbose("Render close, globalNodeTrail(2a):" + ContentWorker.nodeTrailToCsv(globalNodeTrail), "");
}
renderSubContent();
//if (Debug.verboseOn()) Debug.logVerbose("in Render(2), globalNodeTrail ." + getWrapped(env, "globalNodeTrail") , module);
}
public void renderSubContent() throws IOException {
String mimeTypeId = (String) templateRoot.get("mimeTypeId");
Object localeObject = templateRoot.get("locale");
Locale locale = null;
if (localeObject == null) {
locale = UtilHttp.getLocale(request);
} else {
locale = UtilMisc.ensureLocale(localeObject);
}
//TemplateHashModel dataRoot = env.getDataModel();
// Timestamp fromDate = UtilDateTime.nowTimestamp();
// List passedGlobalNodeTrail = (List)templateRoot.get("globalNodeTrail");
String editRequestName = (String)templateRoot.get("editRequestName");
if (Debug.verboseOn()) {
Debug.logVerbose("in Render(3), editRequestName ." + editRequestName , module);
}
/*
GenericValue thisView = null;
if (view != null) {
thisView = view;
} else if (passedGlobalNodeTrail.size() > 0) {
Map map = (Map)passedGlobalNodeTrail.get(passedGlobalNodeTrail.size() - 1);
if (Debug.infoOn()) Debug.logInfo("in Render(3), map ." + map , module);
if (map != null)
thisView = (GenericValue)map.get("value");
}
if (Debug.verboseOn()) Debug.logVerbose("in RenderSubContent, subContentId:" + templateRoot.get("subContentId"), module);
if (Debug.verboseOn()) Debug.logVerbose("in RenderSubContent, contentId:" + templateRoot.get("contentId"), module);
*/
if (UtilValidate.isNotEmpty(editRequestName)) {
String editStyle = getEditStyle();
openEditWrap(out, editStyle);
}
if (Debug.verboseOn()) {
Debug.logVerbose("in RenderSubContent, contentId(2):" + templateRoot.get("contentId"), module);
Debug.logVerbose("in RenderSubContent, subContentId(2):" + templateRoot.get("subContentId"), module);
}
FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
//if (thisView != null) {
try {
String txt = ContentWorker.renderContentAsText(dispatcher, delegator, thisContentId, templateRoot, locale, mimeTypeId, true);
if ("true".equals(xmlEscape)) {
txt = UtilFormatOut.encodeXmlValue(txt);
}
out.write(txt);
// if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, after renderContentAsTextCache:", module);
} catch (GeneralException e) {
String errMsg = "Error rendering thisContentId:" + thisContentId + " msg:" + e.toString();
Debug.logError(e, errMsg, module);
// just log a message and don't return anything: throw new IOException();
}
//}
FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
FreeMarkerWorker.reloadValues(templateRoot, savedValues, env);
if (UtilValidate.isNotEmpty(editRequestName)) {
closeEditWrap(out, editRequestName);
}
//if (Debug.infoOn()) Debug.logInfo("in Render(4), globalNodeTrail ." + getWrapped(env, "globalNodeTrail") , module);
}
public void openEditWrap(Writer out, String editStyle) throws IOException {
String divStr = "<div class=\"" + editStyle + "\">";
out.write(divStr);
}
public void closeEditWrap(Writer out, String editRequestName) throws IOException {
if (Debug.infoOn()) {
Debug.logInfo("in RenderSubContent, contentId(3):" + templateRoot.get("contentId"), module);
Debug.logInfo("in RenderSubContent, subContentId(3):" + templateRoot.get("subContentId"), module);
}
String fullRequest = editRequestName;
String contentId = null;
contentId = (String)templateRoot.get("subContentId");
String delim = "?";
if (UtilValidate.isNotEmpty(contentId)) {
fullRequest += delim + "contentId=" + contentId;
delim = "&";
}
out.write("<a href=\"");
ServletContext servletContext = request.getSession().getServletContext();
RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_");
out.append(rh.makeLink(request, response, "/" + fullRequest, false, false, true));
out.write("\">Edit</a>");
out.write("</div>");
}
public String getEditStyle() {
String editStyle = (String)templateRoot.get("editStyle");
if (UtilValidate.isEmpty(editStyle)) {
editStyle = UtilProperties.getPropertyValue("content", "defaultEditStyle");
}
if (UtilValidate.isEmpty(editStyle)) {
editStyle = "buttontext";
}
return editStyle;
}
};
}
}
@@ -0,0 +1,161 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilFormatOut;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.collections.MapStack;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.webapp.control.RequestHandler;
import freemarker.core.Environment;
import freemarker.template.TemplateTransformModel;
/**
* RenderContentAsText - Freemarker Transform for Content rendering
* This transform cannot be called recursively (at this time).
*/
public class RenderContentTransform implements TemplateTransformModel {
public static final String module = RenderContentTransform.class.getName();
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final Environment env = Environment.getCurrentEnvironment();
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env);
final Map<String, Object> templateRoot = MapStack.create(FreeMarkerWorker.createEnvironmentMap(env));
((MapStack)templateRoot).push(args);
final String xmlEscape = (String)templateRoot.get("xmlEscape");
final String thisContentId = (String)templateRoot.get("contentId");
return new Writer(out) {
@Override
public void write(char cbuf[], int off, int len) {
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
renderSubContent();
}
public void renderSubContent() throws IOException {
String mimeTypeId = (String) templateRoot.get("mimeTypeId");
Object localeObject = templateRoot.get("locale");
Locale locale = null;
if (localeObject == null) {
locale = UtilHttp.getLocale(request);
} else {
locale = UtilMisc.ensureLocale(localeObject);
}
String editRequestName = (String)templateRoot.get("editRequestName");
if (UtilValidate.isNotEmpty(editRequestName)) {
String editStyle = getEditStyle();
openEditWrap(out, editStyle);
}
try {
String txt = null;
String mapKey = (String)templateRoot.get("mapKey");
if (UtilValidate.isEmpty(mapKey)) {
txt = ContentWorker.renderContentAsText(dispatcher, delegator, thisContentId, templateRoot, locale, mimeTypeId, true);
} else {
txt = ContentWorker.renderSubContentAsText(dispatcher, delegator, thisContentId, mapKey, templateRoot, locale, mimeTypeId, true);
}
if ("true".equals(xmlEscape)) {
txt = UtilFormatOut.encodeXmlValue(txt);
}
out.write(txt);
} catch (GeneralException e) {
String errMsg = "Error rendering thisContentId:" + thisContentId + " msg:" + e.toString();
Debug.logError(e, errMsg, module);
// just log a message and don't return anything: throw new IOException();
}
if (UtilValidate.isNotEmpty(editRequestName)) {
closeEditWrap(out, editRequestName);
}
}
public void openEditWrap(Writer out, String editStyle) throws IOException {
String divStr = "<div class=\"" + editStyle + "\">";
out.write(divStr);
}
public void closeEditWrap(Writer out, String editRequestName) throws IOException {
// StringBuilder sb = new StringBuilder();
String fullRequest = editRequestName;
String delim = "?";
if (UtilValidate.isNotEmpty(thisContentId)) {
fullRequest += delim + "contentId=" + thisContentId;
delim = "&";
}
out.write("<a href=\"");
ServletContext servletContext = request.getSession().getServletContext();
RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_");
out.append(rh.makeLink(request, response, "/" + fullRequest, false, false, true));
out.write("\">Edit</a>");
out.write("</div>");
}
public String getEditStyle() {
String editStyle = (String)templateRoot.get("editStyle");
if (UtilValidate.isEmpty(editStyle)) {
editStyle = UtilProperties.getPropertyValue("content", "defaultEditStyle");
}
if (UtilValidate.isEmpty(editStyle)) {
editStyle = "buttontext";
}
return editStyle;
}
};
}
}
@@ -0,0 +1,291 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilFormatOut;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilHttp;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.service.LocalDispatcher;
import freemarker.core.Environment;
import freemarker.template.TemplateTransformModel;
//import com.clarkware.profiler.Profiler;
/**
* RenderSubContentAsText - Freemarker Transform for Content rendering
* This transform cannot be called recursively (at this time).
*/
public class RenderSubContentAsText implements TemplateTransformModel {
public static final String module = RenderSubContentAsText.class.getName();
public static final String [] upSaveKeyNames = {"globalNodeTrail"};
public static final String [] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final Environment env = Environment.getCurrentEnvironment();
// final Map templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
// final Map templateCtx = new HashMap<String, Object>();
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
// final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env);
final Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
if (Debug.infoOn()) {
Debug.logInfo("in RenderSubContent, contentId(0):" + templateRoot.get("contentId"), module);
}
FreeMarkerWorker.getSiteParameters(request, templateRoot);
final Map<String, Object> savedValuesUp = new HashMap<String, Object>();
FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
FreeMarkerWorker.overrideWithArgs(templateRoot, args);
if (Debug.infoOn()) {
Debug.logInfo("in RenderSubContent, contentId(2):" + templateRoot.get("contentId"), module);
}
//final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
//List trail = (List)templateRoot.get("globalNodeTrail");
//if (Debug.infoOn()) Debug.logInfo("in Render(0), globalNodeTrail ." + trail , module);
//String contentAssocPredicateId = (String)templateRoot.get("contentAssocPredicateId");
//String strNullThruDatesOnly = (String)templateRoot.get("nullThruDatesOnly");
//Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && strNullThruDatesOnly.equalsIgnoreCase("true")) ? Boolean.TRUE :Boolean.FALSE;
final String thisContentId = (String)templateRoot.get("contentId");
final String thisMapKey = (String)templateRoot.get("mapKey");
final String xmlEscape = (String)templateRoot.get("xmlEscape");
if (Debug.infoOn()) {
Debug.logInfo("in Render(0), thisSubContentId ." + thisContentId , module);
}
final boolean directAssocMode = UtilValidate.isNotEmpty(thisContentId) ? true : false;
if (Debug.infoOn()) {
Debug.logInfo("in Render(0), directAssocMode ." + directAssocMode , module);
}
/*
GenericValue val = null;
try {
val = FreeMarkerWorker.getCurrentContent(delegator, trail, userLogin, templateRoot, nullThruDatesOnly, contentAssocPredicateId);
} catch (GeneralException e) {
throw new RuntimeException("Error getting current content. " + e.toString());
}
final GenericValue view = val;
String dataResourceId = null;
String subContentIdSub = null;
if (view != null) {
try {
dataResourceId = (String) view.get("drDataResourceId");
} catch (Exception e) {
dataResourceId = (String) view.get("dataResourceId");
}
subContentIdSub = (String) view.get("contentId");
}
// This order is taken so that the dataResourceType can be overridden in the transform arguments.
String subDataResourceTypeId = (String)templateRoot.get("subDataResourceTypeId");
if (UtilValidate.isEmpty(subDataResourceTypeId)) {
try {
subDataResourceTypeId = (String) view.get("drDataResourceTypeId");
} catch (Exception e) {
// view may be "Content"
}
// TODO: If this value is still empty then it is probably necessary to get a value from
// the parent context. But it will already have one and it is the same context that is
// being passed.
}
String mimeTypeId = FreeMarkerWorker.getMimeTypeId(delegator, view, templateRoot);
templateRoot.put("drDataResourceId", dataResourceId);
templateRoot.put("mimeTypeId", mimeTypeId);
templateRoot.put("dataResourceId", dataResourceId);
templateRoot.put("subContentId", subContentIdSub);
templateRoot.put("subDataResourceTypeId", subDataResourceTypeId);
*/
final Map<String, Object> savedValues = new HashMap<String, Object>();
return new Writer(out) {
@Override
public void write(char cbuf[], int off, int len) {
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
if (Debug.infoOn()) {
Debug.logInfo("Render close, globalNodeTrail(2a):" + ContentWorker.nodeTrailToCsv(globalNodeTrail), "");
}
renderSubContent();
//if (Debug.infoOn()) Debug.logInfo("in Render(2), globalNodeTrail ." + getWrapped(env, "globalNodeTrail") , module);
}
public void renderSubContent() throws IOException {
String mimeTypeId = (String) templateRoot.get("mimeTypeId");
Object localeObject = templateRoot.get("locale");
Locale locale = null;
if (localeObject == null) {
locale = UtilHttp.getLocale(request);
} else {
locale = UtilMisc.ensureLocale(localeObject);
}
// TemplateHashModel dataRoot = env.getDataModel();
// Timestamp fromDate = UtilDateTime.nowTimestamp();
// List passedGlobalNodeTrail = (List) templateRoot.get("globalNodeTrail");
String editRequestName = (String)templateRoot.get("editRequestName");
if (Debug.infoOn()) Debug.logInfo("in Render(3), editRequestName ." + editRequestName , module);
if (UtilValidate.isNotEmpty(editRequestName)) {
String editStyle = getEditStyle();
openEditWrap(out, editStyle);
}
FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
try {
String txt = ContentWorker.renderSubContentAsText(dispatcher, delegator, thisContentId, thisMapKey, templateRoot, locale, mimeTypeId, true);
//String txt = ContentWorker.renderSubContentAsTextCache(delegator, thisContentId, thisMapKey, null, templateRoot, locale, mimeTypeId, null, fromDate);
if ("true".equals(xmlEscape)) {
txt = UtilFormatOut.encodeXmlValue(txt);
}
out.write(txt);
if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, after renderContentAsTextCache:", module);
} catch (GeneralException e) {
String errMsg = "Error rendering thisContentId:" + thisContentId + " msg:" + e.toString();
Debug.logError(e, errMsg, module);
//throw new IOException("Error rendering thisContentId:" + thisContentId + " msg:" + e.toString());
}
FreeMarkerWorker.reloadValues(templateRoot, savedValues, env);
FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
if (UtilValidate.isNotEmpty(editRequestName)) {
closeEditWrap(out, editRequestName);
}
//if (Debug.infoOn()) Debug.logInfo("in Render(4), globalNodeTrail ." + getWrapped(env, "globalNodeTrail") , module);
}
public void openEditWrap(Writer out, String editStyle) throws IOException {
String divStr = "<div class=\"" + editStyle + "\">";
out.write(divStr);
}
public void closeEditWrap(Writer out, String editRequestName) throws IOException {
/*
if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, contentId(5):" + templateRoot.get("contentId"), module);
if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, subContentId(5):" + templateRoot.get("subContentId"), module);
StringBuilder sb = new StringBuilder();
String fullRequest = editRequestName;
String contentId = null;
String contentIdTo = null;
String contentAssocTypeId = null;
String mapKey = null;
String fromDate = null;
contentIdTo = (String)templateRoot.get("contentId");
contentAssocTypeId = (String)templateRoot.get("contentAssocTypeId");
mapKey = (String)templateRoot.get("mapKey");
fromDate = (String)templateRoot.get("fromDate");
//if (Debug.infoOn()) Debug.logInfo("in Render(0), view ." + view , module);
if (view != null) {
ModelEntity modelEntity = view.getModelEntity();
if (UtilValidate.isEmpty(contentId) && modelEntity.getField("caContentId") != null)
contentId = view.getString("caContentId");
if (UtilValidate.isEmpty(contentId) && modelEntity.getField("contentId") != null)
contentId = view.getString("contentId");
if (UtilValidate.isEmpty(contentIdTo) && modelEntity.getField("caContentIdTo") != null)
contentIdTo = view.getString("caContentIdTo");
if (UtilValidate.isEmpty(contentIdTo) && modelEntity.getField("contentIdTo") != null)
contentIdTo = view.getString("contentIdTo");
if (UtilValidate.isEmpty(contentAssocTypeId) && modelEntity.getField("caContentAssocTypeId") != null)
contentAssocTypeId = view.getString("caContentAssocTypeId");
if (UtilValidate.isEmpty(contentAssocTypeId) && modelEntity.getField("contentAssocTypeId") != null)
contentAssocTypeId = view.getString("contentAssocTypeId");
if (UtilValidate.isEmpty(mapKey) && modelEntity.getField("caMapKey") != null)
mapKey = view.getString("caMapKey");
if (UtilValidate.isEmpty(mapKey) && modelEntity.getField("mapKey") != null)
mapKey = view.getString("mapKey");
if (UtilValidate.isEmpty(fromDate) && modelEntity.getField("caFromDate") != null)
fromDate = view.getString("caFromDate");
if (UtilValidate.isEmpty(fromDate) && modelEntity.getField("fromDate") != null)
fromDate = view.getString("fromDate");
}
if (Debug.infoOn()) Debug.logInfo("in Render(0), contentIdTo ." + contentIdTo , module);
String delim = "?";
if (UtilValidate.isNotEmpty(contentId)) {
fullRequest += delim + "contentId=" + contentId;
delim = "&";
}
if (UtilValidate.isNotEmpty(contentIdTo)) {
fullRequest += delim + "contentIdTo=" + contentIdTo;
delim = "&";
}
if (UtilValidate.isNotEmpty(contentAssocTypeId)) {
fullRequest += delim + "contentAssocTypeId=" + contentAssocTypeId;
delim = "&";
}
if (UtilValidate.isNotEmpty(mapKey)) {
fullRequest += delim + "mapKey=" + mapKey;
delim = "&";
}
if (UtilValidate.isNotEmpty(fromDate)) {
fullRequest += delim + "fromDate=" + fromDate;
delim = "&";
}
if (Debug.infoOn()) Debug.logInfo("in Render(2), contentIdTo ." + contentIdTo , module);
WidgetWorker.appendOfbizUrl(sb, fullRequest, request, response);
String url = sb.toString();
String link = "<a href=\"" + url + "\">Edit</a>";
out.write(link);
String divStr = "</div>";
out.write(divStr);
*/
}
public String getEditStyle() {
String editStyle = (String)templateRoot.get("editStyle");
if (UtilValidate.isEmpty(editStyle)) {
editStyle = UtilProperties.getPropertyValue("content", "defaultEditStyle");
}
if (UtilValidate.isEmpty(editStyle)) {
editStyle = "buttontext";
}
return editStyle;
}
};
}
}
@@ -0,0 +1,293 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilProperties;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.model.ModelEntity;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.webapp.control.RequestHandler;
import freemarker.core.Environment;
import freemarker.template.TemplateTransformModel;
/**
* RenderSubContentCacheTransform - Freemarker Transform for Content rendering
* This transform cannot be called recursively (at this time).
*/
public class RenderSubContentCacheTransform implements TemplateTransformModel {
public static final String module = RenderSubContentCacheTransform.class.getName();
public static final String [] upSaveKeyNames = {"globalNodeTrail"};
public static final String [] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
// final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
//final Map templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
//final Map templateCtx = new HashMap<String, Object>();
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
final HttpServletResponse response = FreeMarkerWorker.getWrappedObject("response", env);
final Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
//if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, contentId(0):" + templateRoot.get("contentId"), module);
FreeMarkerWorker.getSiteParameters(request, templateRoot);
final Map<String, Object> savedValuesUp = new HashMap<String, Object>();
FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
FreeMarkerWorker.overrideWithArgs(templateRoot, args);
//if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, contentId(2):" + templateRoot.get("contentId"), module);
final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
List<Map<String, ? extends Object>> trail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
//if (Debug.infoOn()) Debug.logInfo("in Render(0), globalNodeTrail ." + trail , module);
String contentAssocPredicateId = (String)templateRoot.get("contentAssocPredicateId");
String strNullThruDatesOnly = (String)templateRoot.get("nullThruDatesOnly");
Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && strNullThruDatesOnly.equalsIgnoreCase("true")) ? Boolean.TRUE :Boolean.FALSE;
String thisSubContentId = (String)templateRoot.get("subContentId");
//if (Debug.infoOn()) Debug.logInfo("in Render(0), thisSubContentId ." + thisSubContentId , module);
final boolean directAssocMode = UtilValidate.isNotEmpty(thisSubContentId) ? true : false;
//if (Debug.infoOn()) Debug.logInfo("in Render(0), directAssocMode ." + directAssocMode , module);
GenericValue val = null;
try {
val = ContentWorker.getCurrentContent(delegator, trail, userLogin, templateRoot, nullThruDatesOnly, contentAssocPredicateId);
} catch (GeneralException e) {
throw new RuntimeException("Error getting current content. " + e.toString());
}
final GenericValue view = val;
String dataResourceId = null;
String subContentIdSub = null;
if (view != null) {
try {
dataResourceId = (String) view.get("drDataResourceId");
} catch (Exception e) {
dataResourceId = (String) view.get("dataResourceId");
}
subContentIdSub = (String) view.get("contentId");
}
// This order is taken so that the dataResourceType can be overridden in the transform arguments.
String subDataResourceTypeId = (String)templateRoot.get("subDataResourceTypeId");
if (UtilValidate.isEmpty(subDataResourceTypeId)) {
try {
subDataResourceTypeId = (String) view.get("drDataResourceTypeId");
} catch (Exception e) {
// view may be "Content"
}
// TODO: If this value is still empty then it is probably necessary to get a value from
// the parent context. But it will already have one and it is the same context that is
// being passed.
}
String mimeTypeId = ContentWorker.getMimeTypeId(delegator, view, templateRoot);
templateRoot.put("drDataResourceId", dataResourceId);
templateRoot.put("mimeTypeId", mimeTypeId);
templateRoot.put("dataResourceId", dataResourceId);
templateRoot.put("subContentId", subContentIdSub);
templateRoot.put("subDataResourceTypeId", subDataResourceTypeId);
//final Map savedValues = new HashMap<String, Object>();
//FreeMarkerWorker.saveContextValues(templateCtx, saveKeyNames, savedValues);
return new Writer(out) {
@Override
public void write(char cbuf[], int off, int len) {
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
// List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
// if (Debug.infoOn()) Debug.logInfo("Render close, globalNodeTrail(2a):" + FreeMarkerWorker.nodeTrailToCsv(globalNodeTrail), "");
try {
renderSubContent();
FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
//if (Debug.infoOn()) Debug.logInfo("in Render(2), globalNodeTrail ." + getWrapped(env, "globalNodeTrail") , module);
} catch (IOException e) {
throw new IOException(e.getMessage());
}
}
public void renderSubContent() throws IOException {
// TemplateHashModel dataRoot = env.getDataModel();
// Timestamp fromDate = UtilDateTime.nowTimestamp();
List<Map<String, ? extends Object>> passedGlobalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
String editRequestName = (String)templateRoot.get("editRequestName");
//if (Debug.infoOn()) Debug.logInfo("in Render(3), editRequestName ." + editRequestName , module);
GenericValue thisView = null;
if (view != null) {
thisView = view;
} else if (passedGlobalNodeTrail.size() > 0) {
Map<String, ? extends Object> map = UtilGenerics.checkMap(passedGlobalNodeTrail.get(passedGlobalNodeTrail.size() - 1));
if (Debug.infoOn()) {
Debug.logInfo("in Render(3), map ." + map , module);
}
if (map != null) {
thisView = (GenericValue)map.get("value");
}
}
//if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, subContentId:" + templateRoot.get("subContentId"), module);
//if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, contentId:" + templateRoot.get("contentId"), module);
String mimeTypeId = (String) templateRoot.get("mimeTypeId");
Locale locale = (Locale) templateRoot.get("locale");
if (locale == null)
locale = Locale.getDefault();
if (UtilValidate.isNotEmpty(editRequestName)) {
String editStyle = getEditStyle();
openEditWrap(out, editStyle);
}
if (thisView != null) {
String contentId = thisView.getString("contentId");
if (contentId != null) {
try {
ContentWorker.renderContentAsText(dispatcher, delegator, contentId, out, templateRoot, locale, mimeTypeId, null, null, true);
//if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, after renderContentAsTextCache:", module);
} catch (GeneralException e) {
Debug.logError(e, "Error rendering content", module);
throw new IOException("Error rendering thisView:" + thisView + " msg:" + e.toString());
}
}
}
if (UtilValidate.isNotEmpty(editRequestName)) {
closeEditWrap(out, editRequestName);
}
//if (Debug.infoOn()) Debug.logInfo("in Render(4), globalNodeTrail ." + getWrapped(env, "globalNodeTrail") , module);
}
public void openEditWrap(Writer out, String editStyle) throws IOException {
String divStr = "<div class=\"" + editStyle + "\">";
out.write(divStr);
}
public void closeEditWrap(Writer out, String editRequestName) throws IOException {
// if (Debug.infoOn()) Debug.logInfo("in RenderSubContent, contentId(1):" + templateRoot.get("contentId"), module);
// if (Debug.infoOn()) Debug.logInfo("in Render(0), templateRoot ." + templateRoot , module);
// StringBuilder sb = new StringBuilder();
String fullRequest = editRequestName;
String contentId = null;
String contentIdTo = null;
String contentAssocTypeId = null;
String mapKey = null;
String fromDate = null;
if (!directAssocMode) {
contentIdTo = (String)templateRoot.get("contentId");
contentAssocTypeId = (String)templateRoot.get("contentAssocTypeId");
mapKey = (String)templateRoot.get("mapKey");
fromDate = (String)templateRoot.get("fromDate");
if (Debug.infoOn()) Debug.logInfo("in Render(0), view ." + view , module);
if (view != null) {
ModelEntity modelEntity = view.getModelEntity();
if (UtilValidate.isEmpty(contentId) && modelEntity.getField("caContentId") != null)
contentId = view.getString("caContentId");
if (UtilValidate.isEmpty(contentId) && modelEntity.getField("contentId") != null)
contentId = view.getString("contentId");
if (UtilValidate.isEmpty(contentIdTo) && modelEntity.getField("caContentIdTo") != null)
contentIdTo = view.getString("caContentIdTo");
if (UtilValidate.isEmpty(contentIdTo) && modelEntity.getField("contentIdTo") != null)
contentIdTo = view.getString("contentIdTo");
if (UtilValidate.isEmpty(contentAssocTypeId) && modelEntity.getField("caContentAssocTypeId") != null)
contentAssocTypeId = view.getString("caContentAssocTypeId");
if (UtilValidate.isEmpty(contentAssocTypeId) && modelEntity.getField("contentAssocTypeId") != null)
contentAssocTypeId = view.getString("contentAssocTypeId");
if (UtilValidate.isEmpty(mapKey) && modelEntity.getField("caMapKey") != null)
mapKey = view.getString("caMapKey");
if (UtilValidate.isEmpty(mapKey) && modelEntity.getField("mapKey") != null)
mapKey = view.getString("mapKey");
if (UtilValidate.isEmpty(fromDate) && modelEntity.getField("caFromDate") != null)
fromDate = view.getString("caFromDate");
if (UtilValidate.isEmpty(fromDate) && modelEntity.getField("fromDate") != null)
fromDate = view.getString("fromDate");
}
} else {
contentId = (String)templateRoot.get("subContentId");
}
if (Debug.infoOn()) Debug.logInfo("in Render(0), contentIdTo ." + contentIdTo , module);
String delim = "?";
if (UtilValidate.isNotEmpty(contentId)) {
fullRequest += delim + "contentId=" + contentId;
delim = "&";
}
if (UtilValidate.isNotEmpty(contentIdTo)) {
fullRequest += delim + "contentIdTo=" + contentIdTo;
delim = "&";
}
if (UtilValidate.isNotEmpty(contentAssocTypeId)) {
fullRequest += delim + "contentAssocTypeId=" + contentAssocTypeId;
delim = "&";
}
if (UtilValidate.isNotEmpty(mapKey)) {
fullRequest += delim + "mapKey=" + mapKey;
delim = "&";
}
if (UtilValidate.isNotEmpty(fromDate)) {
fullRequest += delim + "fromDate=" + fromDate;
delim = "&";
}
if (Debug.infoOn()) Debug.logInfo("in Render(2), contentIdTo ." + contentIdTo , module);
out.write("<a href=\"");
ServletContext servletContext = request.getSession().getServletContext();
RequestHandler rh = (RequestHandler) servletContext.getAttribute("_REQUEST_HANDLER_");
out.append(rh.makeLink(request, response, "/" + fullRequest, false, false, true));
out.write("\">Edit</a>");
out.write("</div>");
}
public String getEditStyle() {
String editStyle = (String)templateRoot.get("editStyle");
if (UtilValidate.isEmpty(editStyle)) {
editStyle = UtilProperties.getPropertyValue("content", "defaultEditStyle");
}
if (UtilValidate.isEmpty(editStyle)) {
editStyle = "buttontext";
}
return editStyle;
}
};
}
}
@@ -0,0 +1,169 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.webapp.website.WebSiteWorker;
import freemarker.core.Environment;
import freemarker.template.TemplateTransformModel;
/**
* RenderSubContentTransform - Freemarker Transform for Content rendering
* This transform cannot be called recursively (at this time).
*/
public class RenderSubContentTransform implements TemplateTransformModel {
public static final String module = RenderSubContentTransform.class.getName();
/**
* @deprecated use FreeMarkerWorker.getArg()
* Does a conditional search to return a value for a parameter with the passed name. Looks first to see if it was passed as an argument to the transform.
* Secondly, it looks to see if it is passed as a parameter in the template context object.
* <p/>
* Note that this is different from the getArg method of EditRenderDataResourceTransform, which checks the request object instead of the template context
* object.
*/
@Deprecated
public static String getArg(Map<String, Object> args, String key, Environment env) {
return FreeMarkerWorker.getArg(args, key, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, Object> args, String key, Map<String, Object> ctx) {
return FreeMarkerWorker.getArg(args, key, ctx);
}
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
// final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
Map<String, Object> ctx = FreeMarkerWorker.getWrappedObject("context", env);
if (ctx == null) {
ctx = new HashMap<String, Object>();
}
final String mapKey = FreeMarkerWorker.getArg(args, "mapKey", ctx);
final String subContentId = FreeMarkerWorker.getArg(args, "subContentId", ctx);
// final String subDataResourceTypeId = FreeMarkerWorker.getArg(args, "subDataResourceTypeId", ctx);
final String contentId = FreeMarkerWorker.getArg(args, "contentId", ctx);
final String mimeTypeId = FreeMarkerWorker.getArg(args, "mimeTypeId", ctx);
final String throwExceptionOnError = FreeMarkerWorker.getArg(args, "throwExceptionOnError", ctx);
final Locale locale = FreeMarkerWorker.getWrappedObject("locale", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
GenericValue subContentDataResourceViewTemp = FreeMarkerWorker.getWrappedObject("subContentDataResourceView", env);
if (subContentDataResourceViewTemp == null) {
List<String> assocTypes = UtilMisc.toList("SUB_CONTENT");
Timestamp fromDate = UtilDateTime.nowTimestamp();
try {
subContentDataResourceViewTemp = ContentWorker.getSubContent(delegator, contentId, mapKey, subContentId, userLogin, assocTypes, fromDate);
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
final GenericValue subContentDataResourceView = subContentDataResourceViewTemp;
final Map<String, Object> templateContext = ctx;
return new Writer(out) {
@Override
public void write(char cbuf[], int off, int len) {
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
try {
renderSubContent();
} catch (IOException e) {
if (!"false".equals(throwExceptionOnError)) {
throw new IOException(e.getMessage());
}
}
}
public void renderSubContent() throws IOException {
// TemplateHashModel dataRoot = env.getDataModel();
// Timestamp fromDate = UtilDateTime.nowTimestamp();
ServletContext servletContext = request.getSession().getServletContext();
String rootDir = servletContext.getRealPath("/");
String webSiteId = WebSiteWorker.getWebSiteId(request);
String https = (String) servletContext.getAttribute("https");
templateContext.put("webSiteId", webSiteId);
templateContext.put("https", https);
templateContext.put("rootDir", rootDir);
Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
templateRoot.put("context", templateContext);
if (subContentDataResourceView != null) {
}
try {
if (subContentId != null) {
ContentWorker.renderContentAsText(dispatcher, delegator, subContentId, out, templateRoot, locale, mimeTypeId, null, null, false);
} else {
ContentWorker.renderSubContentAsText(dispatcher, delegator, contentId, out, mapKey, templateRoot, locale, mimeTypeId, false);
}
//Map results = ContentWorker.renderSubContentAsText(delegator, contentId, out, mapKey, subContentId, subContentDataResourceView, templateRoot, locale, mimeTypeId, userLogin, fromDate);
} catch (GeneralException e) {
Debug.logError(e, "Error rendering content", module);
throw new IOException("Error rendering content" + e.toString());
}
//Map resultCtx = FreeMarkerWorker.getWrappedObject("context", env);
templateContext.put("mapKey", null);
templateContext.put("subContentId", null);
templateContext.put("subDataResourceTypeId", null);
templateContext.put("contentId", contentId);
templateContext.put("mimeTypeId", null);
templateContext.put("locale", locale);
}
};
}
}
@@ -0,0 +1,296 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.webapp.ftl.LoopWriter;
import freemarker.core.Environment;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;
import freemarker.template.TransformControl;
//import com.clarkware.profiler.Profiler;
/**
* TraverseSubContentCacheTransform - Freemarker Transform for URLs (links)
*/
public class TraverseSubContentCacheTransform implements TemplateTransformModel {
public static final String module = TraverseSubContentCacheTransform.class.getName();
public static final String [] upSaveKeyNames = {"globalNodeTrail"};
public static final String [] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
/**
* @deprecated use FreeMarkerWorker.getWrappedObject()
* A wrapper for the FreeMarkerWorker version.
*/
@Deprecated
public static Object getWrappedObject(String varName, Environment env) {
return FreeMarkerWorker.getWrappedObject(varName, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, Object> args, String key, Environment env) {
return FreeMarkerWorker.getArg(args, key, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, Object> args, String key, Map<String, Object> ctx) {
return FreeMarkerWorker.getArg(args, key, ctx);
}
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
//final Map templateRoot = FreeMarkerWorker.getWrappedObject("context", env);
final Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
//FreeMarkerWorker.convertContext(templateRoot);
final Map<String, Object> savedValuesUp = new HashMap<String, Object>();
FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
final Map<String, Object> savedValues = new HashMap<String, Object>();
FreeMarkerWorker.overrideWithArgs(templateRoot, args);
String startContentAssocTypeId = (String)templateRoot.get("contentAssocTypeId");
// if (Debug.infoOn()) Debug.logInfo("in TraverseSubContentCache, startContentAssocTypeId:" + startContentAssocTypeId, module);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
FreeMarkerWorker.getSiteParameters(request, templateRoot);
final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
// List globalNodeTrail = (List)templateRoot.get("globalNodeTrail");
// String csvTrail = ContentWorker.nodeTrailToCsv(globalNodeTrail);
// if (Debug.infoOn()) Debug.logInfo("in Traverse(0), csvTrail:"+csvTrail,module);
String strNullThruDatesOnly = (String)templateRoot.get("nullThruDatesOnly");
String contentAssocPredicateId = (String)templateRoot.get("contentAssocPredicateId");
Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && strNullThruDatesOnly.equalsIgnoreCase("true")) ? Boolean.TRUE :Boolean.FALSE;
try {
// getCurrentContent puts the "current" node on the end of globalNodeTrail.
// It may have already been there, but getCurrentContent will compare its contentId
// to values in templateRoot.
ContentWorker.getCurrentContent(delegator, globalNodeTrail, userLogin, templateRoot, nullThruDatesOnly, contentAssocPredicateId);
} catch (GeneralException e) {
throw new RuntimeException("Error getting current content. " + e.toString());
}
// final GenericValue view = val;
final Map<String, Object> traverseContext = new HashMap<String, Object>();
traverseContext.put("delegator", delegator);
Map<String, Object> whenMap = new HashMap<String, Object>();
whenMap.put("followWhen", templateRoot.get("followWhen"));
whenMap.put("pickWhen", templateRoot.get("pickWhen"));
whenMap.put("returnBeforePickWhen", templateRoot.get("returnBeforePickWhen"));
whenMap.put("returnAfterPickWhen", templateRoot.get("returnAfterPickWhen"));
traverseContext.put("whenMap", whenMap);
env.setVariable("whenMap", FreeMarkerWorker.autoWrap(whenMap, env));
String fromDateStr = (String)templateRoot.get("fromDateStr");
String thruDateStr = (String)templateRoot.get("thruDateStr");
Timestamp fromDate = null;
if (UtilValidate.isNotEmpty(fromDateStr)) {
fromDate = UtilDateTime.toTimestamp(fromDateStr);
}
traverseContext.put("fromDate", fromDate);
Timestamp thruDate = null;
if (UtilValidate.isNotEmpty(thruDateStr)) {
thruDate = UtilDateTime.toTimestamp(thruDateStr);
}
traverseContext.put("thruDate", thruDate);
//if (UtilValidate.isEmpty(startContentAssocTypeId)) {
//throw new RuntimeException("contentAssocTypeId is empty.");
//}
traverseContext.put("contentAssocTypeId", startContentAssocTypeId);
String direction = (String)templateRoot.get("direction");
if (UtilValidate.isEmpty(direction)) {
direction = "From";
}
traverseContext.put("direction", direction);
return new LoopWriter(out) {
@Override
public void write(char cbuf[], int off, int len) {
//StringBuilder ctxBuf = (StringBuilder) templateContext.get("buf");
//ctxBuf.append(cbuf, off, len);
buf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public int onStart() throws TemplateModelException, IOException {
//templateContext.put("buf", new StringBuilder());
List<Map<String, ? extends Object>> nodeTrail = null;
Map<String, Object> node = null;
// GenericValue subContentDataResourceView = null;
List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateRoot.get("globalNodeTrail"));
// String trailCsv = ContentWorker.nodeTrailToCsv(globalNodeTrail);
// if (Debug.infoOn()) Debug.logInfo("in TraverseSubContentCache, onStart, trailCsv(1):" + trailCsv , module);
if (globalNodeTrail.size() > 0) {
int sz = globalNodeTrail.size() ;
nodeTrail = new LinkedList<Map<String,? extends Object>>();
//nodeTrail = passedGlobalNodeTrail.subList(sz - 1, sz);
node = UtilGenerics.checkMap(globalNodeTrail.get(sz - 1));
//if (Debug.infoOn()) Debug.logInfo("in TraverseSubContentCache, onStart, node(1):" + node , module);
Boolean checkedObj = (Boolean)node.get("checked");
Map<String, Object> whenMap = UtilGenerics.checkMap(templateRoot.get("whenMap"));
//if (Debug.infoOn()) Debug.logInfo("in TraverseSubContentCache, whenMap(2):" + whenMap , module);
if (checkedObj == null || !checkedObj.booleanValue()) {
ContentWorker.checkConditions(delegator, node, null, whenMap);
}
} else {
throw new IOException("Empty node trail entries");
}
Boolean isReturnBeforePickBool = (Boolean)node.get("isReturnBeforePick");
if (isReturnBeforePickBool != null && isReturnBeforePickBool.booleanValue()) {
return TransformControl.SKIP_BODY;
}
// GenericValue content = null;
ContentWorker.selectKids(node, traverseContext);
//if (Debug.infoOn()) Debug.logInfo("in TraverseSubContentCache, onStart, node(2):" + node , module);
nodeTrail.add(node);
traverseContext.put("nodeTrail", nodeTrail);
Boolean isPickBool = (Boolean)node.get("isPick");
Boolean isFollowBool = (Boolean)node.get("isFollow");
//if (Debug.infoOn()) Debug.logInfo("in TraverseSubContentCache, onStart, isPickBool(1):" + isPickBool + " isFollowBool:" + isFollowBool, module);
boolean isPick = true;
if ((isPickBool == null || !isPickBool.booleanValue())
&& (isFollowBool != null && isFollowBool.booleanValue())) {
isPick = ContentWorker.traverseSubContent(traverseContext);
//if (Debug.infoOn()) Debug.logInfo("in TraverseSubContentCache, onStart, isPick(2):" + isPick, module);
}
if (isPick) {
populateContext(traverseContext, templateRoot);
FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
return TransformControl.EVALUATE_BODY;
} else {
return TransformControl.SKIP_BODY;
}
}
@Override
public int afterBody() throws TemplateModelException, IOException {
FreeMarkerWorker.reloadValues(templateRoot, savedValues, env);
// List globalNodeTrail = (List)templateRoot.get("globalNodeTrail");
// if (Debug.infoOn()) Debug.logInfo("populateContext, globalNodeTrail(2a):" + FreeMarkerWorker.nodeTrailToCsv(globalNodeTrail), "");
// List<Map<String, ? extends Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail"));
// List savedGlobalNodeTrail = (List)savedValues.get("globalNodeTrail");
// templateRoot.put("globalNodeTrail", savedGlobalNodeTrail);
// int sz = nodeTrail.size();
boolean inProgress = ContentWorker.traverseSubContent(traverseContext);
if (inProgress) {
populateContext(traverseContext, templateRoot);
FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
//globalNodeTrail = (List)templateRoot.get("globalNodeTrail");
//globalNodeTrail.addAll(nodeTrail);
return TransformControl.REPEAT_EVALUATION;
} else {
return TransformControl.END_EVALUATION;
}
}
@Override
public void close() throws IOException {
FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
String wrappedContent = buf.toString();
out.write(wrappedContent);
//if (Debug.infoOn()) Debug.logInfo("in TraverseSubContent, wrappedContent:" + wrappedContent, module);
}
public void populateContext(Map<String, Object> traverseContext, Map<String, Object> templateContext) {
List<Map<String, ? extends Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail"));
// if (Debug.infoOn()) Debug.logInfo("populateContext, nodeTrail csv(a):" + FreeMarkerWorker.nodeTrailToCsv((List)nodeTrail), "");
int sz = nodeTrail.size();
Map<String, ? extends Object> node = nodeTrail.get(sz - 1);
GenericValue content = (GenericValue)node.get("value");
String contentId = (String)node.get("contentId");
// String subContentId = (String)node.get("subContentId");
String contentAssocTypeId = (String)node.get("contentAssocTypeId");
envWrap("contentAssocTypeId", contentAssocTypeId);
envWrap("contentId", contentId);
envWrap("content", content);
String mapKey = (String)node.get("mapKey");
envWrap("mapKey", mapKey);
envWrap("subContentDataResourceView", null);
List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.checkList(templateContext.get("nodeTrail"));
String contentIdEnd = null;
String contentIdStart = null;
if (globalNodeTrail != null) {
Map<String, ? extends Object> ndEnd = globalNodeTrail.get(globalNodeTrail.size() - 1);
contentIdEnd = (String)ndEnd.get("contentId");
Map<String, ? extends Object> ndStart = nodeTrail.get(0);
contentIdStart = (String)ndStart.get("contentId");
} else {
globalNodeTrail = new LinkedList<Map<String,? extends Object>>();
}
//if (Debug.infoOn()) Debug.logInfo("in TraverseSubContentCache, populateContext, contentIdEnd(1):" + contentIdEnd + " contentIdStart:" + contentIdStart + " equals:" + (contentIdStart.equals(contentIdEnd)), module);
boolean bIdEnd = UtilValidate.isNotEmpty(contentIdEnd);
boolean bIdStart = UtilValidate.isNotEmpty(contentIdStart);
boolean bEquals = contentIdStart.equals(contentIdEnd);
// if (Debug.infoOn()) Debug.logInfo("in TraverseSubContentCache, populateContext, contentIdEnd(1):" + bIdEnd + " contentIdStart:" + bIdStart + " equals:" + bEquals, module);
// if (Debug.infoOn()) Debug.logInfo("populateContext, globalNodeTrail(1a):" + FreeMarkerWorker.nodeTrailToCsv(globalNodeTrail), "");
if (bIdEnd && bIdStart && bEquals) {
List<Map<String, ? extends Object>> subList = nodeTrail.subList(1, sz);
globalNodeTrail.addAll(subList);
} else {
globalNodeTrail.addAll(nodeTrail);
}
// if (Debug.infoOn()) Debug.logInfo("populateContext, globalNodeTrail(1b):" + FreeMarkerWorker.nodeTrailToCsv(globalNodeTrail), "");
int indentSz = globalNodeTrail.size();
envWrap("indent", Integer.valueOf(indentSz));
String trailCsv = ContentWorker.nodeTrailToCsv(globalNodeTrail);
//if (Debug.infoOn()) Debug.logInfo("in TraverseSubContentCache, populateCtx, trailCsv(2):" + trailCsv , module);
envWrap("nodeTrailCsv", trailCsv);
envWrap("globalNodeTrail", globalNodeTrail);
}
public void envWrap(String varName, Object obj) {
templateRoot.put(varName, obj);
env.setVariable(varName, FreeMarkerWorker.autoWrap(obj, env));
}
};
}
}
@@ -0,0 +1,351 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityQuery;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.webapp.ftl.LoopWriter;
import freemarker.core.Environment;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateTransformModel;
import freemarker.template.TransformControl;
/**
* TraverseSubContentTransform - Freemarker Transform for URLs (links)
*/
public class TraverseSubContentTransform implements TemplateTransformModel {
public static final String module = TraverseSubContentTransform.class.getName();
public static final String [] saveKeyNames = {"contentId", "subContentId", "mimeType", "subContentDataResourceView", "wrapTemplateId", "templateContentId", "pickWhen", "followWhen", "returnAfterPickWhen", "returnBeforePickWhen", "indent"};
public static final String [] removeKeyNames = {"templateContentId", "subDataResourceTypeId", "mapKey", "wrappedFTL", "nodeTrail"};
/**
* @deprecated use FreeMarkerWorker.getWrappedObject()
* A wrapper for the FreeMarkerWorker version.
*/
@Deprecated
public static Object getWrappedObject(String varName, Environment env) {
return FreeMarkerWorker.getWrappedObject(varName, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, Object> args, String key, Environment env) {
return FreeMarkerWorker.getArg(args, key, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, Object> args, String key, Map<String, Object> ctx) {
return FreeMarkerWorker.getArg(args, key, ctx);
}
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
final Map<String, Object> templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
//FreeMarkerWorker.convertContext(templateCtx);
final Map<String, Object> savedValues = FreeMarkerWorker.saveValues(templateCtx, saveKeyNames);
FreeMarkerWorker.overrideWithArgs(templateCtx, args);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
/*
final String editTemplate = FreeMarkerWorker.getArg(args, "editTemplate", ctx);
final String wrapTemplateId = FreeMarkerWorker.getArg(args, "wrapTemplateId", ctx);
//final String mapKey = FreeMarkerWorker.getArg(args, "mapKey", ctx);
final String templateContentId = FreeMarkerWorker.getArg(args, "templateContentId", ctx);
final String subDataResourceTypeId = FreeMarkerWorker.getArg(args, "subDataResourceTypeId", ctx);
final String contentId = FreeMarkerWorker.getArg(args, "contentId", ctx);
final String subContentId = FreeMarkerWorker.getArg(args, "subContentId", ctx);
final String rootDir = FreeMarkerWorker.getArg(args, "rootDir", ctx);
final String webSiteId = FreeMarkerWorker.getArg(args, "webSiteId", ctx);
final String https = FreeMarkerWorker.getArg(args, "https", ctx);
final String viewSize = FreeMarkerWorker.getArg(args, "viewSize", ctx);
final String viewIndex = FreeMarkerWorker.getArg(args, "viewIndex", ctx);
final String listSize = FreeMarkerWorker.getArg(args, "listSize", ctx);
final String highIndex = FreeMarkerWorker.getArg(args, "highIndex", ctx);
final String lowIndex = FreeMarkerWorker.getArg(args, "lowIndex", ctx);
final String queryString = FreeMarkerWorker.getArg(args, "queryString", ctx);
final Locale locale = FreeMarkerWorker.getWrappedObject("locale", env);
final String mimeTypeId = FreeMarkerWorker.getArg(args, "mimeTypeId", ctx);
*/
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
//final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
GenericValue view = FreeMarkerWorker.getWrappedObject("subContentDataResourceView", env);
final Integer indent = (templateCtx.get("indent") == null) ? Integer.valueOf(0) : (Integer)templateCtx.get("indent");
String contentId = (String)templateCtx.get("contentId");
String subContentId = (String)templateCtx.get("subContentId");
if (view == null) {
String thisContentId = subContentId;
if (UtilValidate.isEmpty(thisContentId)) {
thisContentId = contentId;
}
if (UtilValidate.isNotEmpty(thisContentId)) {
try {
view = EntityQuery.use(delegator).from("Content").where("contentId", thisContentId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Error getting sub-content", module);
throw new RuntimeException(e.getMessage());
}
}
}
final GenericValue subContentDataResourceView = view;
final Map<String, Object> traverseContext = new HashMap<String, Object>();
traverseContext.put("delegator", delegator);
Map<String, Object> whenMap = new HashMap<String, Object>();
whenMap.put("followWhen", templateCtx.get("followWhen"));
whenMap.put("pickWhen", templateCtx.get("pickWhen"));
whenMap.put("returnBeforePickWhen", templateCtx.get("returnBeforePickWhen"));
whenMap.put("returnAfterPickWhen", templateCtx.get("returnAfterPickWhen"));
traverseContext.put("whenMap", whenMap);
String fromDateStr = (String)templateCtx.get("fromDateStr");
String thruDateStr = (String)templateCtx.get("thruDateStr");
Timestamp fromDate = null;
if (UtilValidate.isNotEmpty(fromDateStr)) {
fromDate = UtilDateTime.toTimestamp(fromDateStr);
}
traverseContext.put("fromDate", fromDate);
Timestamp thruDate = null;
if (UtilValidate.isNotEmpty(thruDateStr)) {
thruDate = UtilDateTime.toTimestamp(thruDateStr);
}
traverseContext.put("thruDate", thruDate);
String startContentAssocTypeId = (String)templateCtx.get("contentAssocTypeId");
if (startContentAssocTypeId != null)
startContentAssocTypeId = "SUB_CONTENT";
traverseContext.put("contentAssocTypeId", startContentAssocTypeId);
String direction = (String)templateCtx.get("direction");
if (UtilValidate.isEmpty(direction))
direction = "From";
traverseContext.put("direction", direction);
return new LoopWriter(out) {
@Override
public void write(char cbuf[], int off, int len) {
//StringBuilder ctxBuf = (StringBuilder) templateContext.get("buf");
//ctxBuf.append(cbuf, off, len);
buf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public int onStart() throws TemplateModelException, IOException {
//templateContext.put("buf", new StringBuilder());
List<Map<String, Object>> nodeTrail = new LinkedList<Map<String,Object>>();
traverseContext.put("nodeTrail", nodeTrail);
// GenericValue content = null;
/*
if (UtilValidate.isNotEmpty(contentId)) {
try {
content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
} catch (GenericEntityException e) {
// TODO: Not sure what to put here.
throw new RuntimeException(e.getMessage());
}
}
*/
Map<String, Object> rootNode = ContentWorker.makeNode(subContentDataResourceView);
ContentWorker.traceNodeTrail("1", nodeTrail);
ContentWorker.selectKids(rootNode, traverseContext);
ContentWorker.traceNodeTrail("2", nodeTrail);
nodeTrail.add(rootNode);
boolean isPick = checkWhen(subContentDataResourceView, (String)traverseContext.get("contentAssocTypeId"));
rootNode.put("isPick", Boolean.valueOf(isPick));
if (!isPick) {
ContentWorker.traceNodeTrail("3", nodeTrail);
isPick = ContentWorker.traverseSubContent(traverseContext);
ContentWorker.traceNodeTrail("4", nodeTrail);
}
if (isPick) {
populateContext(traverseContext, templateCtx);
ContentWorker.traceNodeTrail("5", nodeTrail);
return TransformControl.EVALUATE_BODY;
} else {
return TransformControl.SKIP_BODY;
}
}
@Override
public int afterBody() throws TemplateModelException, IOException {
//out.write(buf.toString());
//buf.setLength(0);
//templateContext.put("buf", new StringBuilder());
List<Map<String, Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail"));
ContentWorker.traceNodeTrail("6",nodeTrail);
boolean inProgress = ContentWorker.traverseSubContent(traverseContext);
ContentWorker.traceNodeTrail("7",nodeTrail);
if (inProgress) {
populateContext(traverseContext, templateCtx);
ContentWorker.traceNodeTrail("8",nodeTrail);
return TransformControl.REPEAT_EVALUATION;
} else
return TransformControl.END_EVALUATION;
}
@Override
public void close() throws IOException {
String wrappedFTL = buf.toString();
String encloseWrappedText = (String)templateCtx.get("encloseWrappedText");
if (UtilValidate.isEmpty(encloseWrappedText) || encloseWrappedText.equalsIgnoreCase("false")) {
out.write(wrappedFTL);
wrappedFTL = null; // So it won't get written again below.
}
String wrapTemplateId = (String)templateCtx.get("wrapTemplateId");
if (UtilValidate.isNotEmpty(wrapTemplateId)) {
templateCtx.put("wrappedFTL", wrappedFTL);
Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
/*
templateRoot.put("viewSize", viewSize);
templateRoot.put("viewIndex", viewIndex);
templateRoot.put("listSize", listSize);
templateRoot.put("highIndex", highIndex);
templateRoot.put("lowIndex", lowIndex);
templateRoot.put("queryString", queryString);
templateRoot.put("wrapDataResourceTypeId", subDataResourceTypeId);
templateRoot.put("wrapContentIdTo", contentId);
templateRoot.put("wrapMimeTypeId", mimeTypeId);
//templateRoot.put("wrapMapKey", mapKey);
*/
templateRoot.put("context", templateCtx);
String mimeTypeId = (String) templateCtx.get("mimeTypeId");
Locale locale = (Locale) templateCtx.get("locale");
if (locale == null)
locale = Locale.getDefault();
try {
ContentWorker.renderContentAsText(dispatcher, delegator, wrapTemplateId, out, templateRoot, locale, mimeTypeId, null, null, true);
} catch (GeneralException e) {
Debug.logError(e, "Error rendering content", module);
throw new IOException("Error rendering content" + e.toString());
}
/*
Map resultsCtx = FreeMarkerWorker.getWrappedObject("context", env);
templateContext.put("contentId", contentId);
templateContext.put("locale", locale);
templateContext.put("mapKey", null);
templateContext.put("subContentId", null);
templateContext.put("templateContentId", null);
templateContext.put("subDataResourceTypeId", null);
templateContext.put("mimeTypeId", null);
*/
} else {
if (UtilValidate.isNotEmpty(wrappedFTL))
out.write(wrappedFTL);
}
FreeMarkerWorker.removeValues(templateCtx, removeKeyNames);
FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
}
private boolean checkWhen (GenericValue thisContent, String contentAssocTypeId) {
boolean isPick = false;
Map<String, Object> assocContext = new HashMap<String, Object>();
if (UtilValidate.isEmpty(contentAssocTypeId)) {
contentAssocTypeId = "";
}
assocContext.put("contentAssocTypeId", contentAssocTypeId);
// assocContext.put("contentTypeId", assocValue.get("contentTypeId"));
// String assocRelation = null;
String thisDirection = (String)templateCtx.get("direction");
String thisContentId = (String)templateCtx.get("thisContentId");
// String relatedDirection = null;
if (thisDirection != null && thisDirection.equalsIgnoreCase("From")) {
assocContext.put("contentIdFrom", thisContentId);
// assocRelation = "FromContent";
// relatedDirection = "From";
} else {
assocContext.put("contentIdTo", thisContentId);
// assocRelation = "ToContent";
// relatedDirection = "To";
}
assocContext.put("content", thisContent);
List<Object> purposes = ContentWorker.getPurposes(thisContent);
assocContext.put("purposes", purposes);
List<String> contentTypeAncestry = new LinkedList<String>();
String contentTypeId = (String)thisContent.get("contentTypeId");
try {
ContentWorker.getContentTypeAncestry(delegator, contentTypeId, contentTypeAncestry);
} catch (GenericEntityException e) {
return false;
}
assocContext.put("typeAncestry", contentTypeAncestry);
Map<String, Object> whenMap = UtilGenerics.checkMap(traverseContext.get("whenMap"));
// String pickWhen = (String)whenMap.get("pickWhen");
List<Map<String, ? extends Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail"));
int indentSz = indent.intValue() + nodeTrail.size();
assocContext.put("indentObj", Integer.valueOf(indentSz));
isPick = ContentWorker.checkWhen(assocContext, (String)whenMap.get("pickWhen"), true);
return isPick;
}
public void populateContext(Map<String, Object> traverseContext, Map<String, Object> templateContext) {
List<Map<String, Object>> nodeTrail = UtilGenerics.checkList(traverseContext.get("nodeTrail"));
int sz = nodeTrail.size();
Map<String, Object> node = nodeTrail.get(sz - 1);
// GenericValue content = (GenericValue)node.get("value");
String contentId = (String)node.get("contentId");
// String subContentId = (String)node.get("subContentId");
templateContext.put("subContentId", contentId);
templateContext.put("subContentDataResourceView", null);
int indentSz = indent.intValue() + nodeTrail.size();
templateContext.put("indent", Integer.valueOf(indentSz));
if (sz >= 2) {
Map<String, Object> parentNode = nodeTrail.get(sz - 2);
GenericValue parentContent = (GenericValue)parentNode.get("value");
String parentContentId = (String)parentNode.get("contentId");
templateContext.put("parentContentId", parentContentId);
templateContext.put("parentContent", parentContent);
templateContext.put("nodeTrail", nodeTrail);
}
}
};
}
}
@@ -0,0 +1,205 @@
/*******************************************************************************
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package org.ofbiz.content.webapp.ftl;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.GeneralException;
import org.ofbiz.base.util.UtilGenerics;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.base.util.template.FreeMarkerWorker;
import org.ofbiz.content.content.ContentWorker;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.service.LocalDispatcher;
import freemarker.core.Environment;
import freemarker.template.TemplateTransformModel;
//import com.clarkware.profiler.Profiler;
/**
* WrapSubContentCacheTransform - Freemarker Transform for URLs (links)
*
* This is an interactive FreeMarker tranform that allows the user to modify the contents that are placed within it.
*/
public class WrapSubContentCacheTransform implements TemplateTransformModel {
public static final String module = WrapSubContentCacheTransform.class.getName();
public static final String [] upSaveKeyNames = {"globalNodeTrail"};
public static final String [] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"};
/**
* @deprecated use FreeMarkerWorker.getWrappedObject()
* A wrapper for the FreeMarkerWorker version.
*/
@Deprecated
public static Object getWrappedObject(String varName, Environment env) {
return FreeMarkerWorker.getWrappedObject(varName, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, Object> args, String key, Environment env) {
return FreeMarkerWorker.getArg(args, key, env);
}
/**
* @deprecated use FreeMarkerWorker.getArg()
*/
@Deprecated
public static String getArg(Map<String, Object> args, String key, Map<String, Object> ctx) {
return FreeMarkerWorker.getArg(args, key, ctx);
}
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
Map<String, Object> envContext = FreeMarkerWorker.getWrappedObject("context", env);
final Map<String, Object> templateCtx;
if (envContext == null) {
templateCtx = FreeMarkerWorker.createEnvironmentMap(env);
} else {
templateCtx = envContext;
}
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env);
FreeMarkerWorker.getSiteParameters(request, templateCtx);
final Map<String, Object> savedValuesUp = new HashMap<String, Object>();
FreeMarkerWorker.saveContextValues(templateCtx, upSaveKeyNames, savedValuesUp);
//if (Debug.infoOn()) Debug.logInfo("in Wrap(0a), savedValuesUp ." + savedValuesUp , module);
FreeMarkerWorker.overrideWithArgs(templateCtx, args);
//if (Debug.infoOn()) Debug.logInfo("in Wrap(0b), savedValuesUp ." + savedValuesUp , module);
final String wrapTemplateId = (String)templateCtx.get("wrapTemplateId");
//if (Debug.infoOn()) Debug.logInfo("in WrapSubContent, wrapTemplateId(1):" + wrapTemplateId, module);
final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
List<Map<String, ? extends Object>> trail = UtilGenerics.checkList(templateCtx.get("globalNodeTrail"));
//if (Debug.infoOn()) Debug.logInfo("in WrapSubContent, trail(0):" + trail, "");
String contentAssocPredicateId = (String)templateCtx.get("contentAssocPredicateId");
String strNullThruDatesOnly = (String)templateCtx.get("nullThruDatesOnly");
Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && strNullThruDatesOnly.equalsIgnoreCase("true")) ? Boolean.TRUE :Boolean.FALSE;
GenericValue val = null;
try {
val = ContentWorker.getCurrentContent(delegator, trail, userLogin, templateCtx, nullThruDatesOnly, contentAssocPredicateId);
} catch (GeneralException e) {
throw new RuntimeException("Error getting current content. " + e.toString());
}
//if (Debug.infoOn()) Debug.logInfo("in WrapSubContent, trail(1):" + trail, "");
final GenericValue view = val;
String dataResourceId = null;
try {
dataResourceId = (String) view.get("drDataResourceId");
} catch (Exception e) {
dataResourceId = (String) view.get("dataResourceId");
}
String subContentIdSub = (String) view.get("contentId");
// This order is taken so that the dataResourceType can be overridden in the transform arguments.
String subDataResourceTypeId = (String)templateCtx.get("subDataResourceTypeId");
if (UtilValidate.isEmpty(subDataResourceTypeId)) {
try {
subDataResourceTypeId = (String) view.get("drDataResourceTypeId");
} catch (Exception e) {
// view may be "Content"
}
// TODO: If this value is still empty then it is probably necessary to get a value from
// the parent context. But it will already have one and it is the same context that is
// being passed.
}
final Map<String, Object> savedValues = new HashMap<String, Object>();
FreeMarkerWorker.saveContextValues(templateCtx, saveKeyNames, savedValues);
//if (Debug.infoOn()) Debug.logInfo("in Wrap(1), savedValues ." + savedValues , module);
// This order is taken so that the mimeType can be overridden in the transform arguments.
String mimeTypeId = ContentWorker.getMimeTypeId(delegator, view, templateCtx);
templateCtx.put("drDataResourceId", dataResourceId);
templateCtx.put("mimeTypeId", mimeTypeId);
templateCtx.put("dataResourceId", dataResourceId);
templateCtx.put("subContentIdSub", subContentIdSub);
templateCtx.put("subDataResourceTypeId", subDataResourceTypeId);
templateCtx.put("wrapTemplateId", null); // Not something to pass on
return new Writer(out) {
@Override
public void write(char cbuf[], int off, int len) {
buf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
out.flush();
}
@Override
public void close() throws IOException {
FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
//if (Debug.infoOn()) Debug.logInfo("in Wrap(2), savedValues ." + savedValues , module);
String wrappedContent = buf.toString();
//if (view != null && Debug.infoOn()) Debug.logInfo("in WrapSubContent, view(2):" + view.get("contentId"), module);
//if (Debug.infoOn()) Debug.logInfo("in WrapSubContent, wrappedContent:" + wrappedContent, module);
//if (Debug.infoOn()) Debug.logInfo("in WrapSubContent, wrapTemplateId(2):" + wrapTemplateId, module);
if (UtilValidate.isNotEmpty(wrapTemplateId)) {
templateCtx.put("wrappedContent", wrappedContent);
//Map templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
Map<String, Object> templateRoot = null;
Map<String, Object> templateRootTemplate = UtilGenerics.checkMap(templateCtx.get("templateRootTemplate"));
if (templateRootTemplate == null) {
Map<String, Object> templateRootTmp = FreeMarkerWorker.createEnvironmentMap(env);
templateRoot = UtilMisc.makeMapWritable(templateRootTmp);
templateCtx.put("templateRootTemplate", templateRootTmp);
} else {
templateRoot = UtilMisc.makeMapWritable(templateRootTemplate);
}
templateRoot.put("context", templateCtx);
String mimeTypeId = (String)templateCtx.get("mimeTypeId");
Locale locale = null;
try {
//if (Debug.infoOn()) Debug.logInfo("in Edit(0), before calling renderContentAsText ." , module);
ContentWorker.renderContentAsText(dispatcher, delegator, wrapTemplateId, out, templateRoot, locale, mimeTypeId, null, null, true);
//if (Debug.infoOn()) Debug.logInfo("in Edit(0), after calling renderContentAsText ." , module);
} catch (IOException e) {
Debug.logError(e, "Error rendering content" + e.getMessage(), module);
throw new IOException("Error rendering content" + e.toString());
} catch (GeneralException e2) {
Debug.logError(e2, "Error rendering content" + e2.getMessage(), module);
throw new IOException("Error rendering content" + e2.toString());
}
FreeMarkerWorker.reloadValues(templateCtx, savedValuesUp, env);
//if (Debug.infoOn()) Debug.logInfo("in Wrap(2), savedValuesUp ." + savedValuesUp , module);
}
}
};
}
}