use of org.apache.ofbiz.base.util.string.FlexibleStringExpander in project ofbiz-framework by apache.
the class ProductServices method addAdditionalViewForProduct.
public static Map<String, Object> addAdditionalViewForProduct(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
String productId = (String) context.get("productId");
String productContentTypeId = (String) context.get("productContentTypeId");
ByteBuffer imageData = (ByteBuffer) context.get("uploadedFile");
Locale locale = (Locale) context.get("locale");
if (UtilValidate.isNotEmpty(context.get("_uploadedFile_fileName"))) {
Map<String, Object> imageContext = new HashMap<>();
imageContext.putAll(context);
imageContext.put("delegator", delegator);
imageContext.put("tenantId", delegator.getDelegatorTenantId());
String imageFilenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.additionalviewsize.format", delegator);
String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.server.path", delegator), imageContext);
String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.url.prefix", delegator), imageContext);
imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length() - 1) : imageServerPath;
imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length() - 1) : imageUrlPrefix;
FlexibleStringExpander filenameExpander = FlexibleStringExpander.getInstance(imageFilenameFormat);
String viewNumber = String.valueOf(productContentTypeId.charAt(productContentTypeId.length() - 1));
String viewType = "additional" + viewNumber;
String id = productId;
if (imageFilenameFormat.endsWith("${id}")) {
id = productId + "_View_" + viewNumber;
viewType = "additional";
}
String fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", viewType, "sizetype", "original"));
String filePathPrefix = "";
String filenameToUse = fileLocation;
if (fileLocation.lastIndexOf('/') != -1) {
// adding 1 to include the trailing slash
filePathPrefix = fileLocation.substring(0, fileLocation.lastIndexOf('/') + 1);
filenameToUse = fileLocation.substring(fileLocation.lastIndexOf('/') + 1);
}
List<GenericValue> fileExtension;
try {
fileExtension = EntityQuery.use(delegator).from("FileExtension").where("mimeTypeId", (String) context.get("_uploadedFile_contentType")).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
GenericValue extension = EntityUtil.getFirst(fileExtension);
if (extension != null) {
filenameToUse += "." + extension.getString("fileExtensionId");
}
/* Write the new image file */
String targetDirectory = imageServerPath + "/" + filePathPrefix;
try {
File targetDir = new File(targetDirectory);
// Create the new directory
if (!targetDir.exists()) {
boolean created = targetDir.mkdirs();
if (!created) {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_create_target_directory", locale) + " - " + targetDirectory;
Debug.logFatal(errMsg, module);
return ServiceUtil.returnError(errMsg);
}
// Delete existing image files
// Images are ordered by productId (${location}/${id}/${viewtype}/${sizetype})
} else if (!filenameToUse.contains(productId)) {
try {
File[] files = targetDir.listFiles();
for (File file : files) {
if (file.isFile()) {
if (!file.delete()) {
Debug.logError("File : " + file.getName() + ", couldn't be deleted", module);
}
}
}
} catch (SecurityException e) {
Debug.logError(e, module);
}
// Images aren't ordered by productId (${location}/${viewtype}/${sizetype}/${id})
} else {
try {
File[] files = targetDir.listFiles();
for (File file : files) {
if (file.isFile() && file.getName().startsWith(productId + "_View_" + viewNumber)) {
if (!file.delete()) {
Debug.logError("File : " + file.getName() + ", couldn't be deleted", module);
}
}
}
} catch (SecurityException e) {
Debug.logError(e, module);
}
}
} catch (NullPointerException e) {
Debug.logError(e, module);
}
// Write
try {
File file = new File(imageServerPath + "/" + fileLocation + "." + extension.getString("fileExtensionId"));
try {
RandomAccessFile out = new RandomAccessFile(file, "rw");
out.write(imageData.array());
out.close();
} catch (FileNotFoundException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewUnableWriteFile", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
} catch (IOException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewUnableWriteBinaryData", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
} catch (NullPointerException e) {
Debug.logError(e, module);
}
/* scale Image in different sizes */
Map<String, Object> resultResize = new HashMap<>();
try {
resultResize.putAll(ScaleImage.scaleImageInAllSize(imageContext, filenameToUse, "additional", viewNumber));
} catch (IOException e) {
Debug.logError(e, "Scale additional image in all different sizes is impossible : " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewScaleImpossible", UtilMisc.toMap("errorString", e.toString()), locale));
} catch (JDOMException e) {
Debug.logError(e, "Errors occur in parsing ImageProperties.xml : " + e.toString(), module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewParsingError", UtilMisc.toMap("errorString", e.toString()), locale));
}
String imageUrl = imageUrlPrefix + "/" + fileLocation + "." + extension.getString("fileExtensionId");
/* store the imageUrl version of the image, for backwards compatibility with code that does not use scaled versions */
Map<String, Object> result = addImageResource(dispatcher, delegator, context, imageUrl, productContentTypeId);
if (ServiceUtil.isError(result)) {
return result;
}
/* now store the image versions created by ScaleImage.scaleImageInAllSize */
/* have to shrink length of productContentTypeId, as otherwise value is too long for database field */
Map<String, String> imageUrlMap = UtilGenerics.checkMap(resultResize.get("imageUrlMap"));
for (String sizeType : ScaleImage.sizeTypeList) {
imageUrl = imageUrlMap.get(sizeType);
if (UtilValidate.isNotEmpty(imageUrl)) {
try {
GenericValue productContentType = EntityQuery.use(delegator).from("ProductContentType").where("productContentTypeId", "XTRA_IMG_" + viewNumber + "_" + sizeType.toUpperCase(Locale.getDefault())).cache().queryOne();
if (UtilValidate.isNotEmpty(productContentType)) {
result = addImageResource(dispatcher, delegator, context, imageUrl, "XTRA_IMG_" + viewNumber + "_" + sizeType.toUpperCase(Locale.getDefault()));
if (ServiceUtil.isError(result)) {
Debug.logError(ServiceUtil.getErrorMessage(result), module);
return result;
}
}
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
}
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.base.util.string.FlexibleStringExpander in project ofbiz-framework by apache.
the class ProductServices method addImageForProductPromo.
public static Map<String, Object> addImageForProductPromo(DispatchContext dctx, Map<String, ? extends Object> context) {
LocalDispatcher dispatcher = dctx.getDispatcher();
Delegator delegator = dctx.getDelegator();
GenericValue userLogin = (GenericValue) context.get("userLogin");
String productPromoId = (String) context.get("productPromoId");
String productPromoContentTypeId = (String) context.get("productPromoContentTypeId");
ByteBuffer imageData = (ByteBuffer) context.get("uploadedFile");
String contentId = (String) context.get("contentId");
Locale locale = (Locale) context.get("locale");
if (UtilValidate.isNotEmpty(context.get("_uploadedFile_fileName"))) {
Map<String, Object> imageContext = new HashMap<>();
imageContext.putAll(context);
imageContext.put("tenantId", delegator.getDelegatorTenantId());
String imageFilenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.format", delegator);
String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.server.path", delegator), imageContext);
String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.url.prefix", delegator), imageContext);
imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length() - 1) : imageServerPath;
imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length() - 1) : imageUrlPrefix;
FlexibleStringExpander filenameExpander = FlexibleStringExpander.getInstance(imageFilenameFormat);
String id = productPromoId + "_Image_" + productPromoContentTypeId.charAt(productPromoContentTypeId.length() - 1);
String fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "type", "promo", "id", id));
String filePathPrefix = "";
String filenameToUse = fileLocation;
if (fileLocation.lastIndexOf('/') != -1) {
// adding 1 to include
filePathPrefix = fileLocation.substring(0, fileLocation.lastIndexOf('/') + 1);
// the trailing slash
filenameToUse = fileLocation.substring(fileLocation.lastIndexOf('/') + 1);
}
List<GenericValue> fileExtension;
try {
fileExtension = EntityQuery.use(delegator).from("FileExtension").where("mimeTypeId", EntityOperator.EQUALS, (String) context.get("_uploadedFile_contentType")).queryList();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
GenericValue extension = EntityUtil.getFirst(fileExtension);
if (extension != null) {
filenameToUse += "." + extension.getString("fileExtensionId");
}
File makeResourceDirectory = new File(imageServerPath + "/" + filePathPrefix);
if (!makeResourceDirectory.exists()) {
if (!makeResourceDirectory.mkdirs()) {
Debug.logError("Directory :" + makeResourceDirectory.getPath() + ", couldn't be created", module);
}
}
File file = new File(imageServerPath + "/" + filePathPrefix + filenameToUse);
try {
RandomAccessFile out = new RandomAccessFile(file, "rw");
out.write(imageData.array());
out.close();
} catch (FileNotFoundException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewUnableWriteFile", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
} catch (IOException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewUnableWriteBinaryData", UtilMisc.toMap("fileName", file.getAbsolutePath()), locale));
}
String imageUrl = imageUrlPrefix + "/" + filePathPrefix + filenameToUse;
if (UtilValidate.isNotEmpty(imageUrl) && imageUrl.length() > 0) {
Map<String, Object> dataResourceCtx = new HashMap<>();
dataResourceCtx.put("objectInfo", imageUrl);
dataResourceCtx.put("dataResourceName", context.get("_uploadedFile_fileName"));
dataResourceCtx.put("userLogin", userLogin);
Map<String, Object> productPromoContentCtx = new HashMap<>();
productPromoContentCtx.put("productPromoId", productPromoId);
productPromoContentCtx.put("productPromoContentTypeId", productPromoContentTypeId);
productPromoContentCtx.put("fromDate", context.get("fromDate"));
productPromoContentCtx.put("thruDate", context.get("thruDate"));
productPromoContentCtx.put("userLogin", userLogin);
if (UtilValidate.isNotEmpty(contentId)) {
GenericValue content = null;
try {
content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (content != null) {
GenericValue dataResource = null;
try {
dataResource = content.getRelatedOne("DataResource", false);
} catch (GenericEntityException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
if (dataResource != null) {
dataResourceCtx.put("dataResourceId", dataResource.getString("dataResourceId"));
try {
Map<String, Object> serviceResult = dispatcher.runSync("updateDataResource", dataResourceCtx);
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
} else {
dataResourceCtx.put("dataResourceTypeId", "SHORT_TEXT");
dataResourceCtx.put("mimeTypeId", "text/html");
Map<String, Object> dataResourceResult;
try {
dataResourceResult = dispatcher.runSync("createDataResource", dataResourceCtx);
if (ServiceUtil.isError(dataResourceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(dataResourceResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
Map<String, Object> contentCtx = new HashMap<>();
contentCtx.put("contentId", contentId);
contentCtx.put("dataResourceId", dataResourceResult.get("dataResourceId"));
contentCtx.put("userLogin", userLogin);
try {
Map<String, Object> serviceResult = dispatcher.runSync("updateContent", contentCtx);
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
productPromoContentCtx.put("contentId", contentId);
try {
Map<String, Object> serviceResult = dispatcher.runSync("updateProductPromoContent", productPromoContentCtx);
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
} else {
dataResourceCtx.put("dataResourceTypeId", "SHORT_TEXT");
dataResourceCtx.put("mimeTypeId", "text/html");
Map<String, Object> dataResourceResult;
try {
dataResourceResult = dispatcher.runSync("createDataResource", dataResourceCtx);
if (ServiceUtil.isError(dataResourceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(dataResourceResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
Map<String, Object> contentCtx = new HashMap<>();
contentCtx.put("contentTypeId", "DOCUMENT");
contentCtx.put("dataResourceId", dataResourceResult.get("dataResourceId"));
contentCtx.put("userLogin", userLogin);
Map<String, Object> contentResult;
try {
contentResult = dispatcher.runSync("createContent", contentCtx);
if (ServiceUtil.isError(contentResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(contentResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
productPromoContentCtx.put("contentId", contentResult.get("contentId"));
try {
Map<String, Object> serviceResult = dispatcher.runSync("createProductPromoContent", productPromoContentCtx);
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
}
} else {
Map<String, Object> productPromoContentCtx = new HashMap<>();
productPromoContentCtx.put("productPromoId", productPromoId);
productPromoContentCtx.put("productPromoContentTypeId", productPromoContentTypeId);
productPromoContentCtx.put("contentId", contentId);
productPromoContentCtx.put("fromDate", context.get("fromDate"));
productPromoContentCtx.put("thruDate", context.get("thruDate"));
productPromoContentCtx.put("userLogin", userLogin);
try {
Map<String, Object> serviceResult = dispatcher.runSync("updateProductPromoContent", productPromoContentCtx);
if (ServiceUtil.isError(serviceResult)) {
return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
}
} catch (GenericServiceException e) {
Debug.logError(e, module);
return ServiceUtil.returnError(e.getMessage());
}
}
return ServiceUtil.returnSuccess();
}
use of org.apache.ofbiz.base.util.string.FlexibleStringExpander in project ofbiz-framework by apache.
the class ScaleImage method scaleImageInAllSize.
/**
* scaleImageInAllSize
* <p>
* Scale the original image into all different size Types (small, medium, large, detail)
*
* @param context Context
* @param filenameToUse Filename of future image files
* @param viewType "Main" view or "additional" view
* @param viewNumber If it's the main view, viewNumber = "0"
* @return URL images for all different size types
* @throws IllegalArgumentException Any parameter is null
* @throws ImagingOpException The transform is non-invertible
* @throws IOException Error prevents the document from being fully parsed
* @throws JDOMException Errors occur in parsing
*/
public static Map<String, Object> scaleImageInAllSize(Map<String, ? extends Object> context, String filenameToUse, String viewType, String viewNumber) throws IllegalArgumentException, ImagingOpException, IOException, JDOMException {
/* VARIABLES */
Locale locale = (Locale) context.get("locale");
int index;
Map<String, Map<String, String>> imgPropertyMap = new HashMap<>();
BufferedImage bufImg, bufNewImg;
double imgHeight, imgWidth;
Map<String, String> imgUrlMap = new HashMap<>();
Map<String, Object> resultXMLMap = new HashMap<>();
Map<String, Object> resultBufImgMap = new HashMap<>();
Map<String, Object> resultScaleImgMap = new HashMap<>();
Map<String, Object> result = new HashMap<>();
/* ImageProperties.xml */
String fileName = "component://product/config/ImageProperties.xml";
String imgPropertyFullPath = FlexibleLocation.resolveLocation(fileName).getFile();
resultXMLMap.putAll(ImageTransform.getXMLValue(imgPropertyFullPath, locale));
if (resultXMLMap.containsKey("responseMessage") && "success".equals(resultXMLMap.get("responseMessage"))) {
imgPropertyMap.putAll(UtilGenerics.<Map<String, Map<String, String>>>cast(resultXMLMap.get("xml")));
} else {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_parse", locale) + " : ImageProperties.xml";
Debug.logError(errMsg, module);
result.put(ModelService.ERROR_MESSAGE, errMsg);
return result;
}
/* IMAGE */
// get Name and Extension
index = filenameToUse.lastIndexOf('.');
String imgExtension = filenameToUse.substring(index + 1);
// paths
Map<String, Object> imageContext = new HashMap<>();
imageContext.putAll(context);
imageContext.put("tenantId", ((Delegator) context.get("delegator")).getDelegatorTenantId());
String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.server.path", (Delegator) context.get("delegator")), imageContext);
String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.url.prefix", (Delegator) context.get("delegator")), imageContext);
imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length() - 1) : imageServerPath;
imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length() - 1) : imageUrlPrefix;
FlexibleStringExpander filenameExpander;
String fileLocation = null;
String id = null;
if (viewType.toLowerCase(Locale.getDefault()).contains("main")) {
String filenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.format", (Delegator) context.get("delegator"));
filenameExpander = FlexibleStringExpander.getInstance(filenameFormat);
id = (String) context.get("productId");
fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "type", "original"));
} else if (viewType.toLowerCase(Locale.getDefault()).contains("additional") && viewNumber != null && !"0".equals(viewNumber)) {
String filenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.additionalviewsize.format", (Delegator) context.get("delegator"));
filenameExpander = FlexibleStringExpander.getInstance(filenameFormat);
id = (String) context.get("productId");
if (filenameFormat.endsWith("${id}")) {
id = id + "_View_" + viewNumber;
} else {
viewType = "additional" + viewNumber;
}
fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", viewType, "sizetype", "original"));
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewType", UtilMisc.toMap("viewType", viewType), locale));
}
if (fileLocation.lastIndexOf('/') != -1) {
// adding 1 to include the trailing slash
fileLocation = fileLocation.substring(0, fileLocation.lastIndexOf('/') + 1);
}
/* get original BUFFERED IMAGE */
resultBufImgMap.putAll(ImageTransform.getBufferedImage(imageServerPath + "/" + fileLocation + "." + imgExtension, locale));
if (resultBufImgMap.containsKey("responseMessage") && "success".equals(resultBufImgMap.get("responseMessage"))) {
bufImg = (BufferedImage) resultBufImgMap.get("bufferedImage");
// get Dimensions
imgHeight = bufImg.getHeight();
imgWidth = bufImg.getWidth();
if (imgHeight == 0.0 || imgWidth == 0.0) {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.one_current_image_dimension_is_null", locale) + " : imgHeight = " + imgHeight + " ; imgWidth = " + imgWidth;
Debug.logError(errMsg, module);
result.put(ModelService.ERROR_MESSAGE, errMsg);
return result;
}
/* Scale image for each size from ImageProperties.xml */
for (Map.Entry<String, Map<String, String>> entry : imgPropertyMap.entrySet()) {
String sizeType = entry.getKey();
// Scale
resultScaleImgMap.putAll(ImageTransform.scaleImage(bufImg, imgHeight, imgWidth, imgPropertyMap, sizeType, locale));
/* Write the new image file */
if (resultScaleImgMap.containsKey("responseMessage") && "success".equals(resultScaleImgMap.get("responseMessage"))) {
bufNewImg = (BufferedImage) resultScaleImgMap.get("bufferedImage");
// Build full path for the new scaled image
String newFileLocation = null;
filenameToUse = sizeType + filenameToUse.substring(filenameToUse.lastIndexOf('.'));
if (viewType.toLowerCase(Locale.getDefault()).contains("main")) {
newFileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "type", sizeType));
} else if (viewType.toLowerCase(Locale.getDefault()).contains("additional")) {
newFileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", viewType, "sizetype", sizeType));
}
String newFilePathPrefix = "";
if (newFileLocation != null && newFileLocation.lastIndexOf('/') != -1) {
// adding 1 to include the trailing slash
newFilePathPrefix = newFileLocation.substring(0, newFileLocation.lastIndexOf('/') + 1);
}
// Directory
String targetDirectory = imageServerPath + "/" + newFilePathPrefix;
try {
// Create the new directory
File targetDir = new File(targetDirectory);
if (!targetDir.exists()) {
boolean created = targetDir.mkdirs();
if (!created) {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_create_target_directory", locale) + " - " + targetDirectory;
Debug.logFatal(errMsg, module);
return ServiceUtil.returnError(errMsg);
}
// Delete existing image files
// Images aren't ordered by productId (${location}/${viewtype}/${sizetype}/${id}) !!! BE CAREFUL !!!
} else if (newFileLocation.endsWith("/" + id)) {
try {
File[] files = targetDir.listFiles();
for (File file : files) {
if (file.isFile() && file.getName().startsWith(id)) {
if (!file.delete()) {
Debug.logError("File :" + file.getName() + ", couldn't be deleted", module);
}
}
}
} catch (SecurityException e) {
Debug.logError(e, module);
}
}
} catch (NullPointerException e) {
Debug.logError(e, module);
}
// write new image
try {
ImageIO.write(bufNewImg, imgExtension, new File(imageServerPath + "/" + newFileLocation + "." + imgExtension));
} catch (IllegalArgumentException e) {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.one_parameter_is_null", locale) + e.toString();
Debug.logError(errMsg, module);
result.put(ModelService.ERROR_MESSAGE, errMsg);
return result;
} catch (IOException e) {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.error_occurs_during_writing", locale) + e.toString();
Debug.logError(errMsg, module);
result.put(ModelService.ERROR_MESSAGE, errMsg);
return result;
}
// Save each Url
if (sizeTypeList.contains(sizeType)) {
String imageUrl = imageUrlPrefix + "/" + newFileLocation + "." + imgExtension;
imgUrlMap.put(sizeType, imageUrl);
}
}
// scaleImgMap
}
// Loop over sizeType
result.put("responseMessage", "success");
result.put("imageUrlMap", imgUrlMap);
result.put("original", resultBufImgMap);
return result;
} else {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_scale_original_image", locale) + " : " + filenameToUse;
Debug.logError(errMsg, module);
result.put(ModelService.ERROR_MESSAGE, errMsg);
return ServiceUtil.returnError(errMsg);
}
}
use of org.apache.ofbiz.base.util.string.FlexibleStringExpander in project ofbiz-framework by apache.
the class ScaleImage method scaleImageManageInAllSize.
public static Map<String, Object> scaleImageManageInAllSize(Map<String, ? extends Object> context, String filenameToUse, String viewType, String viewNumber, String imageType) throws IllegalArgumentException, ImagingOpException, IOException, JDOMException {
/* VARIABLES */
Locale locale = (Locale) context.get("locale");
List<String> sizeTypeList = null;
if (UtilValidate.isNotEmpty(imageType)) {
sizeTypeList = UtilMisc.toList(imageType);
} else {
sizeTypeList = UtilMisc.toList("small", "medium", "large", "detail");
}
int index;
Map<String, Map<String, String>> imgPropertyMap = new HashMap<>();
BufferedImage bufImg, bufNewImg;
double imgHeight, imgWidth;
Map<String, String> imgUrlMap = new HashMap<>();
Map<String, Object> resultXMLMap = new HashMap<>();
Map<String, Object> resultBufImgMap = new HashMap<>();
Map<String, Object> resultScaleImgMap = new HashMap<>();
Map<String, Object> result = new HashMap<>();
/* ImageProperties.xml */
String fileName = "component://product/config/ImageProperties.xml";
String imgPropertyFullPath = FlexibleLocation.resolveLocation(fileName).getFile();
resultXMLMap.putAll(ImageTransform.getXMLValue(imgPropertyFullPath, locale));
if (resultXMLMap.containsKey("responseMessage") && "success".equals(resultXMLMap.get("responseMessage"))) {
imgPropertyMap.putAll(UtilGenerics.<Map<String, Map<String, String>>>cast(resultXMLMap.get("xml")));
} else {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_parse", locale) + " : ImageProperties.xml";
Debug.logError(errMsg, module);
result.put(ModelService.ERROR_MESSAGE, errMsg);
return result;
}
/* IMAGE */
// get Name and Extension
index = filenameToUse.lastIndexOf('.');
String imgName = filenameToUse.substring(0, index - 1);
String imgExtension = filenameToUse.substring(index + 1);
// paths
Map<String, Object> imageContext = new HashMap<>();
imageContext.putAll(context);
imageContext.put("tenantId", ((Delegator) context.get("delegator")).getDelegatorTenantId());
String mainFilenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.format", (Delegator) context.get("delegator"));
String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.server.path", (Delegator) context.get("delegator")), imageContext);
String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.url.prefix", (Delegator) context.get("delegator")), imageContext);
imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length() - 1) : imageServerPath;
imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length() - 1) : imageUrlPrefix;
String id = null;
String type = null;
if (viewType.toLowerCase().contains("main")) {
type = "original";
id = imgName;
} else if (viewType.toLowerCase(Locale.getDefault()).contains("additional") && viewNumber != null && !"0".equals(viewNumber)) {
type = "additional";
id = imgName + "_View_" + viewNumber;
} else {
return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ProductImageViewType", UtilMisc.toMap("viewType", type), locale));
}
FlexibleStringExpander mainFilenameExpander = FlexibleStringExpander.getInstance(mainFilenameFormat);
String fileLocation = mainFilenameExpander.expandString(UtilMisc.toMap("location", "products", "id", context.get("productId"), "type", type));
String filePathPrefix = "";
if (fileLocation.lastIndexOf('/') != -1) {
// adding 1 to include the trailing slash
filePathPrefix = fileLocation.substring(0, fileLocation.lastIndexOf('/') + 1);
}
if (context.get("contentId") != null) {
resultBufImgMap.putAll(ImageTransform.getBufferedImage(imageServerPath + "/" + context.get("productId") + "/" + context.get("clientFileName"), locale));
} else {
/* get original BUFFERED IMAGE */
resultBufImgMap.putAll(ImageTransform.getBufferedImage(imageServerPath + "/" + filePathPrefix + filenameToUse, locale));
}
if (resultBufImgMap.containsKey("responseMessage") && "success".equals(resultBufImgMap.get("responseMessage"))) {
bufImg = (BufferedImage) resultBufImgMap.get("bufferedImage");
// get Dimensions
imgHeight = bufImg.getHeight();
imgWidth = bufImg.getWidth();
if (imgHeight == 0.0 || imgWidth == 0.0) {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.one_current_image_dimension_is_null", locale) + " : imgHeight = " + imgHeight + " ; imgWidth = " + imgWidth;
Debug.logError(errMsg, module);
result.put(ModelService.ERROR_MESSAGE, errMsg);
return result;
}
// new Filename Format
FlexibleStringExpander addFilenameExpander = mainFilenameExpander;
if (viewType.toLowerCase(Locale.getDefault()).contains("additional")) {
String addFilenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.additionalviewsize.format", (Delegator) context.get("delegator"));
addFilenameExpander = FlexibleStringExpander.getInstance(addFilenameFormat);
}
/* scale Image for each Size Type */
for (String sizeType : sizeTypeList) {
resultScaleImgMap.putAll(ImageTransform.scaleImage(bufImg, imgHeight, imgWidth, imgPropertyMap, sizeType, locale));
if (resultScaleImgMap.containsKey("responseMessage") && "success".equals(resultScaleImgMap.get("responseMessage"))) {
bufNewImg = (BufferedImage) resultScaleImgMap.get("bufferedImage");
// write the New Scaled Image
String newFileLocation = null;
if (viewType.toLowerCase(Locale.getDefault()).contains("main")) {
newFileLocation = mainFilenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "type", sizeType));
} else if (viewType.toLowerCase(Locale.getDefault()).contains("additional")) {
newFileLocation = addFilenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", viewType, "sizetype", sizeType));
}
String newFilePathPrefix = "";
if (newFileLocation != null && newFileLocation.lastIndexOf('/') != -1) {
// adding 1 to include the trailing slash
newFilePathPrefix = newFileLocation.substring(0, newFileLocation.lastIndexOf('/') + 1);
}
String targetDirectory = imageServerPath + "/" + newFilePathPrefix;
File targetDir = new File(targetDirectory);
if (!targetDir.exists()) {
boolean created = targetDir.mkdirs();
if (!created) {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_create_target_directory", locale) + " - " + targetDirectory;
Debug.logFatal(errMsg, module);
return ServiceUtil.returnError(errMsg);
}
}
// write new image
try {
ImageIO.write(bufNewImg, imgExtension, new File(imageServerPath + "/" + newFilePathPrefix + filenameToUse));
} catch (IllegalArgumentException e) {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.one_parameter_is_null", locale) + e.toString();
Debug.logError(errMsg, module);
result.put(ModelService.ERROR_MESSAGE, errMsg);
return result;
} catch (IOException e) {
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.error_occurs_during_writing", locale) + e.toString();
Debug.logError(errMsg, module);
result.put(ModelService.ERROR_MESSAGE, errMsg);
return result;
}
/* write Return Result */
String imageUrl = imageUrlPrefix + "/" + newFilePathPrefix + filenameToUse;
imgUrlMap.put(sizeType, imageUrl);
}
// scaleImgMap
}
// sizeIter
result.put("responseMessage", "success");
result.put("imageUrlMap", imgUrlMap);
result.put("original", resultBufImgMap);
return result;
}
String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_scale_original_image", locale) + " : " + filenameToUse;
Debug.logError(errMsg, module);
result.put(ModelService.ERROR_MESSAGE, errMsg);
return ServiceUtil.returnError(errMsg);
}
use of org.apache.ofbiz.base.util.string.FlexibleStringExpander in project ofbiz-framework by apache.
the class FieldToResult method exec.
@Override
public boolean exec(MethodContext methodContext) throws MiniLangException {
Object fieldVal = this.fieldFma.get(methodContext.getEnvMap());
if (fieldVal != null) {
if (this.resultFma.containsNestedExpression()) {
/*
* Replace FMA nested expression functionality with our own.
* The nested expression must be evaluated once using the
* method context, [methodContext.getEnvMap()] then again to
* place the value in the result Map [methodContext.getResults()].
*/
FlexibleStringExpander fse = FlexibleStringExpander.getInstance(this.resultFma.getOriginalName());
String expression = fse.expandString(methodContext.getEnvMap());
FlexibleMapAccessor<Object> resultFma = FlexibleMapAccessor.getInstance(expression);
resultFma.put(methodContext.getResults(), fieldVal);
} else {
this.resultFma.put(methodContext.getResults(), fieldVal);
}
}
return true;
}
Aggregations