use of org.apache.ofbiz.base.util.StringUtil.StringWrapper in project ofbiz-framework by apache.
the class CatalogUrlSeoTransform method initCategoryMap.
public static synchronized void initCategoryMap(HttpServletRequest request, Delegator delegator) {
if (SeoConfigUtil.checkCategoryUrl()) {
categoryNameIdMap = new Hashtable<>();
categoryIdNameMap = new Hashtable<>();
Perl5Matcher matcher = new Perl5Matcher();
try {
Collection<GenericValue> allCategories = delegator.findList("ProductCategory", null, UtilMisc.toSet("productCategoryId", "categoryName"), null, null, false);
for (GenericValue category : allCategories) {
String categoryName = category.getString("categoryName");
String categoryNameId = null;
String categoryIdName = null;
String categoryId = category.getString("productCategoryId");
if (UtilValidate.isNotEmpty(categoryName)) {
categoryName = SeoUrlUtil.replaceSpecialCharsUrl(categoryName.trim());
if (matcher.matches(categoryName, asciiPattern)) {
categoryIdName = categoryName.replaceAll(" ", URL_HYPHEN);
categoryNameId = categoryIdName + URL_HYPHEN + categoryId.trim().replaceAll(" ", URL_HYPHEN);
} else {
categoryIdName = categoryId.trim().replaceAll(" ", URL_HYPHEN);
categoryNameId = categoryIdName;
}
} else {
GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", categoryId).cache().queryOne();
CategoryContentWrapper wrapper = new CategoryContentWrapper(productCategory, request);
StringWrapper alternativeUrl = wrapper.get("ALTERNATIVE_URL", "url");
if (UtilValidate.isNotEmpty(alternativeUrl) && UtilValidate.isNotEmpty(alternativeUrl.toString())) {
categoryIdName = SeoUrlUtil.replaceSpecialCharsUrl(alternativeUrl.toString());
categoryNameId = categoryIdName + URL_HYPHEN + categoryId.trim().replaceAll(" ", URL_HYPHEN);
} else {
categoryNameId = categoryId.trim().replaceAll(" ", URL_HYPHEN);
categoryIdName = categoryNameId;
}
}
if (categoryNameIdMap.containsKey(categoryNameId)) {
categoryNameId = categoryId.trim().replaceAll(" ", URL_HYPHEN);
categoryIdName = categoryNameId;
}
if (!matcher.matches(categoryNameId, asciiPattern) || categoryNameIdMap.containsKey(categoryNameId)) {
continue;
}
categoryNameIdMap.put(categoryNameId, categoryId);
categoryIdNameMap.put(categoryId, categoryIdName);
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
}
}
categoryMapInitialed = true;
}
use of org.apache.ofbiz.base.util.StringUtil.StringWrapper in project ofbiz-framework by apache.
the class CatalogUrlFilter method makeProductUrl.
public static String makeProductUrl(ProductContentWrapper wrapper, List<String> trail, String contextPath, String previousCategoryId, String productCategoryId, String productId) {
String url = "";
StringWrapper alternativeUrl = wrapper.get("ALTERNATIVE_URL", "url");
if (UtilValidate.isNotEmpty(alternativeUrl) && UtilValidate.isNotEmpty(alternativeUrl.toString())) {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(contextPath);
if (urlBuilder.length() == 0 || urlBuilder.charAt(urlBuilder.length() - 1) != '/') {
urlBuilder.append("/");
}
// append alternative URL
url = UrlServletHelper.invalidCharacter(alternativeUrl.toString());
urlBuilder.append(url);
if (UtilValidate.isNotEmpty(productId)) {
urlBuilder.append("-");
urlBuilder.append(productId);
urlBuilder.append("-p");
}
url = urlBuilder.toString();
} else {
if (UtilValidate.isEmpty(trail)) {
trail = new LinkedList<String>();
}
url = CatalogUrlServlet.makeCatalogUrl(contextPath, trail, productId, productCategoryId, previousCategoryId);
}
return url;
}
use of org.apache.ofbiz.base.util.StringUtil.StringWrapper in project ofbiz-framework by apache.
the class CatalogUrlFilter method makeCategoryUrl.
public static String makeCategoryUrl(Delegator delegator, CategoryContentWrapper wrapper, List<String> trail, String contextPath, String previousCategoryId, String productCategoryId, String productId, String viewSize, String viewIndex, String viewSort, String searchString) {
String url = "";
StringWrapper alternativeUrl = wrapper.get("ALTERNATIVE_URL", "url");
if (UtilValidate.isNotEmpty(alternativeUrl) && UtilValidate.isNotEmpty(alternativeUrl.toString())) {
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append(contextPath);
if (urlBuilder.length() == 0 || urlBuilder.charAt(urlBuilder.length() - 1) != '/') {
urlBuilder.append("/");
}
// append alternative URL
url = UrlServletHelper.invalidCharacter(alternativeUrl.toString());
urlBuilder.append(url);
if (UtilValidate.isNotEmpty(productCategoryId)) {
urlBuilder.append("-");
urlBuilder.append(productCategoryId);
urlBuilder.append("-c");
}
// append view index
if (UtilValidate.isNotEmpty(viewIndex)) {
if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) {
urlBuilder.append("?");
}
urlBuilder.append("viewIndex=" + viewIndex + "&");
}
// append view size
if (UtilValidate.isNotEmpty(viewSize)) {
if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) {
urlBuilder.append("?");
}
urlBuilder.append("viewSize=" + viewSize + "&");
}
// append view sort
if (UtilValidate.isNotEmpty(viewSort)) {
if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) {
urlBuilder.append("?");
}
urlBuilder.append("viewSort=" + viewSort + "&");
}
// append search string
if (UtilValidate.isNotEmpty(searchString)) {
if (!urlBuilder.toString().endsWith("?") && !urlBuilder.toString().endsWith("&")) {
urlBuilder.append("?");
}
urlBuilder.append("searchString=" + searchString + "&");
}
if (urlBuilder.toString().endsWith("&")) {
return urlBuilder.toString().substring(0, urlBuilder.toString().length() - 1);
}
url = urlBuilder.toString();
} else {
if (UtilValidate.isEmpty(trail)) {
trail = new LinkedList<String>();
}
url = CatalogUrlServlet.makeCatalogUrl(contextPath, trail, productId, productCategoryId, previousCategoryId);
}
return url;
}
use of org.apache.ofbiz.base.util.StringUtil.StringWrapper in project ofbiz-framework by apache.
the class DataResourceWorker method renderDataResourceAsText.
public static void renderDataResourceAsText(LocalDispatcher dispatcher, Delegator delegator, String dataResourceId, Appendable out, Map<String, Object> templateContext, Locale locale, String targetMimeTypeId, boolean cache, List<GenericValue> webAnalytics) throws GeneralException, IOException {
if (delegator == null) {
delegator = dispatcher.getDelegator();
}
if (dataResourceId == null) {
throw new GeneralException("Cannot lookup data resource with for a null dataResourceId");
}
if (templateContext == null) {
templateContext = new HashMap<>();
}
if (UtilValidate.isEmpty(targetMimeTypeId)) {
targetMimeTypeId = "text/html";
}
if (locale == null) {
locale = Locale.getDefault();
}
// FIXME correctly propagate the theme, then fixes also the related FIXME below
VisualTheme visualTheme = ThemeFactory.getVisualThemeFromId("COMMON");
ModelTheme modelTheme = visualTheme.getModelTheme();
// if the target mimeTypeId is not a text type, throw an exception
if (!targetMimeTypeId.startsWith("text/")) {
throw new GeneralException("The desired mime-type is not a text type, cannot render as text: " + targetMimeTypeId);
}
// get the data resource object
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache(cache).queryOne();
if (dataResource == null) {
throw new GeneralException("No data resource object found for dataResourceId: [" + dataResourceId + "]");
}
// a data template attached to the data resource
String dataTemplateTypeId = dataResource.getString("dataTemplateTypeId");
// no template; or template is NONE; render the data
if (UtilValidate.isEmpty(dataTemplateTypeId) || "NONE".equals(dataTemplateTypeId)) {
DataResourceWorker.writeDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, out, cache);
} else {
// a template is defined; render the template first
templateContext.put("mimeTypeId", targetMimeTypeId);
// FTL template
if ("FTL".equals(dataTemplateTypeId)) {
try {
// get the template data for rendering
String templateText = getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache);
// if use web analytics.
if (UtilValidate.isNotEmpty(webAnalytics)) {
StringBuffer newTemplateText = new StringBuffer(templateText);
String webAnalyticsCode = "<script language=\"JavaScript\" type=\"text/javascript\">";
for (GenericValue webAnalytic : webAnalytics) {
StringWrapper wrapString = StringUtil.wrapString((String) webAnalytic.get("webAnalyticsCode"));
webAnalyticsCode += wrapString.toString();
}
webAnalyticsCode += "</script>";
newTemplateText.insert(templateText.lastIndexOf("</head>"), webAnalyticsCode);
templateText = newTemplateText.toString();
}
// render the FTL template
boolean useTemplateCache = cache && !UtilProperties.getPropertyAsBoolean("content", "disable.ftl.template.cache", false);
// Do not use dataResource.lastUpdatedStamp for dataResource template caching as it may use ftl file or electronicText
// If dataResource using ftl file use nowTimestamp to avoid freemarker caching
Timestamp lastUpdatedStamp = UtilDateTime.nowTimestamp();
// If dataResource is type of ELECTRONIC_TEXT then only use the lastUpdatedStamp of electronicText entity for freemarker caching
if ("ELECTRONIC_TEXT".equals(dataResource.getString("dataResourceTypeId"))) {
GenericValue electronicText = dataResource.getRelatedOne("ElectronicText", true);
if (electronicText != null) {
lastUpdatedStamp = electronicText.getTimestamp("lastUpdatedStamp");
}
}
FreeMarkerWorker.renderTemplateFromString("delegator:" + delegator.getDelegatorName() + ":DataResource:" + dataResourceId, templateText, templateContext, out, lastUpdatedStamp.getTime(), useTemplateCache);
} catch (TemplateException e) {
throw new GeneralException("Error rendering FTL template", e);
}
} else if ("XSLT".equals(dataTemplateTypeId)) {
File targetFileLocation = new File(System.getProperty("ofbiz.home") + "/runtime/tempfiles/docbook.css");
// This is related with the other FIXME above: we need to correctly propagate the theme.
String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator);
visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
modelTheme = visualTheme.getModelTheme();
String docbookStylesheet = modelTheme.getProperty("VT_DOCBOOKSTYLESHEET").toString();
File sourceFileLocation = new File(System.getProperty("ofbiz.home") + "/themes" + docbookStylesheet.substring(1, docbookStylesheet.length() - 1));
UtilMisc.copyFile(sourceFileLocation, targetFileLocation);
// get the template data for rendering
String templateLocation = DataResourceWorker.getContentFile(dataResource.getString("dataResourceTypeId"), dataResource.getString("objectInfo"), (String) templateContext.get("contextRoot")).toString();
// render the XSLT template and file
String outDoc = null;
try {
outDoc = XslTransform.renderTemplate(templateLocation, (String) templateContext.get("docFile"));
} catch (TransformerException c) {
Debug.logError("XSL TransformerException: " + c.getMessage(), module);
}
out.append(outDoc);
// Screen Widget template
} else if ("SCREEN_COMBINED".equals(dataTemplateTypeId)) {
try {
MapStack<String> context = MapStack.create(templateContext);
context.put("locale", locale);
// prepare the map for preRenderedContent
String textData = (String) context.get("textData");
if (UtilValidate.isNotEmpty(textData)) {
Map<String, Object> prc = new HashMap<>();
String mapKey = (String) context.get("mapKey");
if (mapKey != null) {
prc.put(mapKey, mapKey);
}
// used for default screen defs
prc.put("body", textData);
context.put("preRenderedContent", prc);
}
// get the screen renderer; or create a new one
ScreenRenderer screens = (ScreenRenderer) context.get("screens");
if (screens == null) {
// TODO: replace "screen" to support dynamic rendering of different output
ScreenStringRenderer screenStringRenderer = new MacroScreenRenderer(modelTheme.getType("screen"), modelTheme.getScreenRendererLocation("screen"));
screens = new ScreenRenderer(out, context, screenStringRenderer);
screens.getContext().put("screens", screens);
}
// render the screen
ModelScreen modelScreen = null;
ScreenStringRenderer renderer = screens.getScreenStringRenderer();
String combinedName = dataResource.getString("objectInfo");
if ("URL_RESOURCE".equals(dataResource.getString("dataResourceTypeId")) && UtilValidate.isNotEmpty(combinedName) && combinedName.startsWith("component://")) {
modelScreen = ScreenFactory.getScreenFromLocation(combinedName);
} else {
// stored in a single file, long or short text
Document screenXml = UtilXml.readXmlDocument(getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache), true, true);
Map<String, ModelScreen> modelScreenMap = ScreenFactory.readScreenDocument(screenXml, "DataResourceId: " + dataResource.getString("dataResourceId"));
if (UtilValidate.isNotEmpty(modelScreenMap)) {
// get first entry, only one screen allowed per file
Map.Entry<String, ModelScreen> entry = modelScreenMap.entrySet().iterator().next();
modelScreen = entry.getValue();
}
}
if (UtilValidate.isNotEmpty(modelScreen)) {
modelScreen.renderScreenString(out, context, renderer);
} else {
throw new GeneralException("The dataResource file [" + dataResourceId + "] could not be found");
}
} catch (SAXException | ParserConfigurationException e) {
throw new GeneralException("Error rendering Screen template", e);
} catch (TemplateException e) {
throw new GeneralException("Error creating Screen renderer", e);
}
} else if ("FORM_COMBINED".equals(dataTemplateTypeId)) {
try {
Map<String, Object> context = UtilGenerics.checkMap(templateContext.get("globalContext"));
context.put("locale", locale);
context.put("simpleEncoder", UtilCodec.getEncoder(modelTheme.getEncoder("screen")));
HttpServletRequest request = (HttpServletRequest) context.get("request");
HttpServletResponse response = (HttpServletResponse) context.get("response");
ModelForm modelForm = null;
ModelReader entityModelReader = delegator.getModelReader();
String formText = getDataResourceText(dataResource, targetMimeTypeId, locale, templateContext, delegator, cache);
Document formXml = UtilXml.readXmlDocument(formText, true, true);
Map<String, ModelForm> modelFormMap = FormFactory.readFormDocument(formXml, entityModelReader, dispatcher.getDispatchContext(), null);
if (UtilValidate.isNotEmpty(modelFormMap)) {
// get first entry, only one form allowed per file
Map.Entry<String, ModelForm> entry = modelFormMap.entrySet().iterator().next();
modelForm = entry.getValue();
}
String formrenderer = modelTheme.getFormRendererLocation("screen");
MacroFormRenderer renderer = new MacroFormRenderer(formrenderer, request, response);
FormRenderer formRenderer = new FormRenderer(modelForm, renderer);
formRenderer.render(out, context);
} catch (SAXException | ParserConfigurationException e) {
throw new GeneralException("Error rendering Screen template", e);
} catch (TemplateException e) {
throw new GeneralException("Error creating Screen renderer", e);
} catch (Exception e) {
throw new GeneralException("Error rendering Screen template", e);
}
} else {
throw new GeneralException("The dataTemplateTypeId [" + dataTemplateTypeId + "] is not yet supported");
}
}
}
use of org.apache.ofbiz.base.util.StringUtil.StringWrapper in project ofbiz-framework by apache.
the class CatalogUrlSeoTransform method makeProductUrl.
/**
* This is used when building product url in services.
*
* @param delegator
* @param wrapper
* @param prefix
* @param contextPath
* @param currentCategoryId
* @param previousCategoryId
* @param productId
* @return
*/
public static String makeProductUrl(Delegator delegator, ProductContentWrapper wrapper, String prefix, String contextPath, String currentCategoryId, String previousCategoryId, String productId) {
StringBuilder urlBuilder = new StringBuilder();
GenericValue product = null;
urlBuilder.append(prefix);
if (urlBuilder.charAt(urlBuilder.length() - 1) != '/') {
urlBuilder.append("/");
}
if (UtilValidate.isNotEmpty(productId)) {
try {
product = EntityQuery.use(delegator).from("Product").where("productId", productId).cache().queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, "Error looking up product info for productId [" + productId + "]: " + e.toString(), module);
}
}
if (product != null) {
urlBuilder.append(CatalogUrlServlet.PRODUCT_REQUEST + "/");
}
if (UtilValidate.isNotEmpty(currentCategoryId)) {
List<String> trail = null;
trail = CategoryWorker.adjustTrail(null, currentCategoryId, previousCategoryId);
if (!SeoConfigUtil.isCategoryUrlEnabled(contextPath)) {
for (String trailCategoryId : trail) {
if ("TOP".equals(trailCategoryId)) {
continue;
}
urlBuilder.append("/");
urlBuilder.append(trailCategoryId);
}
} else {
if (trail != null && trail.size() > 1) {
String lastCategoryId = trail.get(trail.size() - 1);
if (!"TOP".equals(lastCategoryId)) {
if (SeoConfigUtil.isCategoryNameEnabled()) {
String categoryName = CatalogUrlSeoTransform.getCategoryIdNameMap().get(lastCategoryId);
if (UtilValidate.isNotEmpty(categoryName)) {
urlBuilder.append(categoryName);
if (product != null) {
urlBuilder.append(URL_HYPHEN);
}
}
}
}
}
}
}
if (UtilValidate.isNotEmpty(productId)) {
if (product != null) {
String productName = product.getString("productName");
productName = SeoUrlUtil.replaceSpecialCharsUrl(productName);
if (UtilValidate.isNotEmpty(productName)) {
urlBuilder.append(productName + URL_HYPHEN);
} else {
StringWrapper alternativeUrl = wrapper.get("ALTERNATIVE_URL", "url");
if (UtilValidate.isNotEmpty(alternativeUrl) && UtilValidate.isNotEmpty(alternativeUrl.toString())) {
productName = SeoUrlUtil.replaceSpecialCharsUrl(alternativeUrl.toString());
if (UtilValidate.isNotEmpty(productName)) {
urlBuilder.append(productName + URL_HYPHEN);
}
}
}
}
try {
urlBuilder.append(productId);
} catch (Exception e) {
urlBuilder.append(productId);
}
}
if (!urlBuilder.toString().endsWith("/") && UtilValidate.isNotEmpty(SeoConfigUtil.getCategoryUrlSuffix())) {
urlBuilder.append(SeoConfigUtil.getCategoryUrlSuffix());
}
return urlBuilder.toString();
}
Aggregations