use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class DataResourceWorker method renderMimeTypeTemplate.
public static String renderMimeTypeTemplate(GenericValue mimeTypeTemplate, Map<String, Object> context) throws GeneralException, IOException {
String location = mimeTypeTemplate.getString("templateLocation");
StringWriter writer = new StringWriter();
try {
FreeMarkerWorker.renderTemplate(location, context, writer);
} catch (TemplateException e) {
throw new GeneralException(e.getMessage(), e);
}
return writer.toString();
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class DataResourceWorker method getContentFile.
public static File getContentFile(String dataResourceTypeId, String objectInfo, String contextRoot) throws GeneralException, FileNotFoundException {
File file = null;
if ("LOCAL_FILE".equals(dataResourceTypeId) || "LOCAL_FILE_BIN".equals(dataResourceTypeId)) {
file = FileUtil.getFile(objectInfo);
if (!file.exists()) {
throw new FileNotFoundException("No file found: " + (objectInfo));
}
if (!file.isAbsolute()) {
throw new GeneralException("File (" + objectInfo + ") is not absolute");
}
} else if ("OFBIZ_FILE".equals(dataResourceTypeId) || "OFBIZ_FILE_BIN".equals(dataResourceTypeId)) {
String prefix = System.getProperty("ofbiz.home");
String sep = "";
if (objectInfo.indexOf('/') != 0 && prefix.lastIndexOf('/') != (prefix.length() - 1)) {
sep = "/";
}
file = FileUtil.getFile(prefix + sep + objectInfo);
if (!file.exists()) {
throw new FileNotFoundException("No file found: " + (prefix + sep + objectInfo));
}
} else if ("CONTEXT_FILE".equals(dataResourceTypeId) || "CONTEXT_FILE_BIN".equals(dataResourceTypeId)) {
if (UtilValidate.isEmpty(contextRoot)) {
throw new GeneralException("Cannot find CONTEXT_FILE with an empty context root!");
}
String sep = "";
if (objectInfo.indexOf('/') != 0 && contextRoot.lastIndexOf('/') != (contextRoot.length() - 1)) {
sep = "/";
}
file = FileUtil.getFile(contextRoot + sep + objectInfo);
if (!file.exists()) {
throw new FileNotFoundException("No file found: " + (contextRoot + sep + objectInfo));
}
}
return file;
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class DataResourceWorker method getDataResourceStream.
// ----------------------------
// Data Resource Streaming
// ----------------------------
/**
* getDataResourceStream - gets an InputStream and Content-Length of a DataResource
*
* @param dataResource
* @param https
* @param webSiteId
* @param locale
* @param contextRoot
* @return Map containing 'stream': the InputStream and 'length' a Long containing the content-length
* @throws IOException
* @throws GeneralException
*/
public static Map<String, Object> getDataResourceStream(GenericValue dataResource, String https, String webSiteId, Locale locale, String contextRoot, boolean cache) throws IOException, GeneralException {
if (dataResource == null) {
throw new GeneralException("Cannot stream null data resource!");
}
String dataResourceTypeId = dataResource.getString("dataResourceTypeId");
String dataResourceId = dataResource.getString("dataResourceId");
Delegator delegator = dataResource.getDelegator();
// first text based data
if (dataResourceTypeId.endsWith("_TEXT") || "LINK".equals(dataResourceTypeId)) {
String text = "";
if ("SHORT_TEXT".equals(dataResourceTypeId) || "LINK".equals(dataResourceTypeId)) {
text = dataResource.getString("objectInfo");
} else if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)) {
GenericValue electronicText = EntityQuery.use(delegator).from("ElectronicText").where("dataResourceId", dataResourceId).cache(cache).queryOne();
if (electronicText != null) {
text = electronicText.getString("textData");
}
} else {
throw new GeneralException("Unsupported TEXT type; cannot stream");
}
byte[] bytes = text.getBytes(UtilIO.getUtf8());
return UtilMisc.toMap("stream", new ByteArrayInputStream(bytes), "length", Long.valueOf(bytes.length));
// object (binary) data
}
if (dataResourceTypeId.endsWith("_OBJECT")) {
byte[] bytes = new byte[0];
GenericValue valObj;
if ("IMAGE_OBJECT".equals(dataResourceTypeId)) {
valObj = EntityQuery.use(delegator).from("ImageDataResource").where("dataResourceId", dataResourceId).cache(cache).queryOne();
if (valObj != null) {
bytes = valObj.getBytes("imageData");
}
} else if ("VIDEO_OBJECT".equals(dataResourceTypeId)) {
valObj = EntityQuery.use(delegator).from("VideoDataResource").where("dataResourceId", dataResourceId).cache(cache).queryOne();
if (valObj != null) {
bytes = valObj.getBytes("videoData");
}
} else if ("AUDIO_OBJECT".equals(dataResourceTypeId)) {
valObj = EntityQuery.use(delegator).from("AudioDataResource").where("dataResourceId", dataResourceId).cache(cache).queryOne();
if (valObj != null) {
bytes = valObj.getBytes("audioData");
}
} else if ("OTHER_OBJECT".equals(dataResourceTypeId)) {
valObj = EntityQuery.use(delegator).from("OtherDataResource").where("dataResourceId", dataResourceId).cache(cache).queryOne();
if (valObj != null) {
bytes = valObj.getBytes("dataResourceContent");
}
} else {
throw new GeneralException("Unsupported OBJECT type [" + dataResourceTypeId + "]; cannot stream");
}
return UtilMisc.toMap("stream", new ByteArrayInputStream(bytes), "length", Long.valueOf(bytes.length));
// file data
} else if (dataResourceTypeId.endsWith("_FILE") || dataResourceTypeId.endsWith("_FILE_BIN")) {
String objectInfo = dataResource.getString("objectInfo");
if (UtilValidate.isNotEmpty(objectInfo)) {
File file = DataResourceWorker.getContentFile(dataResourceTypeId, objectInfo, contextRoot);
return UtilMisc.toMap("stream", Files.newInputStream(file.toPath(), StandardOpenOption.READ), "length", Long.valueOf(file.length()));
}
throw new GeneralException("No objectInfo found for FILE type [" + dataResourceTypeId + "]; cannot stream");
// URL resource data
} else if ("URL_RESOURCE".equals(dataResourceTypeId)) {
String objectInfo = dataResource.getString("objectInfo");
if (UtilValidate.isNotEmpty(objectInfo)) {
URL url = new URL(objectInfo);
if (url.getHost() == null) {
// is relative
String newUrl = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https);
if (!newUrl.endsWith("/")) {
newUrl = newUrl + "/";
}
newUrl = newUrl + url.toString();
url = new URL(newUrl);
}
URLConnection con = url.openConnection();
return UtilMisc.toMap("stream", con.getInputStream(), "length", Long.valueOf(con.getContentLength()));
}
throw new GeneralException("No objectInfo found for URL_RESOURCE type; cannot stream");
}
// unsupported type
throw new GeneralException("The dataResourceTypeId [" + dataResourceTypeId + "] is not supported in getDataResourceStream");
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class LimitedSubContentCacheTransform method getWriter.
@Override
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
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<>();
FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp);
final Map<String, Object> savedValues = new HashMap<>();
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<>();
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<>();
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);
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);
Map<String, Object> results = null;
String contentAssocPredicateId = (String) templateRoot.get("contentAssocPredicateId");
try {
results = ContentServicesComplex.getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, null, "From", fromDate, null, assocTypes, null, Boolean.TRUE, contentAssocPredicateId, orderBy);
} catch (MiniLangException | GenericEntityException e) {
throw new RuntimeException(e.getMessage(), e);
}
List<GenericValue> longList = UtilGenerics.checkList(results.get("entityList"));
templateRoot.put("entityList", longList);
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 {
boolean inProgress = false;
if (pickedEntityIds.size() < returnLimit) {
inProgress = getNextMatchingEntity(templateRoot, delegator, env);
}
FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
if (inProgress) {
return TransformControl.EVALUATE_BODY;
}
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));
boolean inProgress = false;
if (pickedEntityIds.size() < returnLimit) {
inProgress = getNextMatchingEntity(templateRoot, delegator, env);
}
FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues);
if (inProgress) {
return TransformControl.REPEAT_EVALUATION;
}
return TransformControl.END_EVALUATION;
}
@Override
public void close() throws IOException {
FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
String wrappedContent = buf.toString();
out.write(wrappedContent);
}
public boolean prepCtx(Delegator delegator, Map<String, Object> ctx, Environment env, GenericValue view) throws GeneralException {
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"));
ContentWorker.checkConditions(delegator, trailNode, null, whenMap);
Boolean isReturnBeforeObj = (Boolean) trailNode.get("isReturnBefore");
Boolean isPickObj = (Boolean) trailNode.get("isPick");
Boolean isFollowObj = (Boolean) trailNode.get("isFollow");
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<>();
}
globalNodeTrail.add(trailNode);
ctx.put("globalNodeTrail", globalNodeTrail);
String csvTrail = ContentWorker.nodeTrailToCsv(globalNodeTrail);
ctx.put("nodeTrailCsv", 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;
}
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();
int idx = (int) (lst.size() * randomValue);
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;
}
};
}
use of org.apache.ofbiz.base.util.GeneralException in project ofbiz-framework by apache.
the class RenderSubContentAsText method getWriter.
@SuppressWarnings("unchecked")
public Writer getWriter(final Writer out, Map args) {
final Environment env = Environment.getCurrentEnvironment();
final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", 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 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);
}
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();
}
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 (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, thisContentId, thisMapKey, 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);
}
FreeMarkerWorker.reloadValues(templateRoot, savedValues, env);
FreeMarkerWorker.reloadValues(templateRoot, savedValuesUp, env);
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 {
}
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;
}
};
}
Aggregations