svn commit: r757089 [2/6] - in /ofbiz/trunk/applications/product/src: ./ org/ofbiz/product/catalog/ org/ofbiz/product/category/ org/ofbiz/product/config/ org/ofbiz/product/feature/ org/ofbiz/product/image/ org/ofbiz/product/inventory/ org/ofbiz/product...

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

svn commit: r757089 [2/6] - in /ofbiz/trunk/applications/product/src: ./ org/ofbiz/product/catalog/ org/ofbiz/product/category/ org/ofbiz/product/config/ org/ofbiz/product/feature/ org/ofbiz/product/image/ org/ofbiz/product/inventory/ org/ofbiz/product...

doogie-3
Modified: ofbiz/trunk/applications/product/src/org/ofbiz/product/feature/ProductFeatureServices.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/product/src/org/ofbiz/product/feature/ProductFeatureServices.java?rev=757089&r1=757088&r2=757089&view=diff
==============================================================================
--- ofbiz/trunk/applications/product/src/org/ofbiz/product/feature/ProductFeatureServices.java (original)
+++ ofbiz/trunk/applications/product/src/org/ofbiz/product/feature/ProductFeatureServices.java Sat Mar 21 23:44:24 2009
@@ -6,9 +6,9 @@
  * 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
@@ -51,7 +51,7 @@
 
     public static final String module = ProductFeatureServices.class.getName();
     public static final String resource = "ProductUiLabels";
-    
+
     /*
      * Parameters: productFeatureCategoryId, productFeatureGroupId, productId, productFeatureApplTypeId
      * Result: productFeaturesByType, a Map of all product features from productFeatureCategoryId, group by productFeatureType -> List of productFeatures
@@ -68,11 +68,11 @@
          */
         String valueToSearch = (String) context.get("productFeatureCategoryId");
         String productFeatureApplTypeId = (String) context.get("productFeatureApplTypeId");
-        
+
         String entityToSearch = "ProductFeature";
         String fieldToSearch = "productFeatureCategoryId";
         List<String> orderBy = UtilMisc.toList("productFeatureTypeId", "description");
-        
+
         if (valueToSearch == null && context.get("productFeatureGroupId") != null) {
             entityToSearch = "ProductFeatureGroupAndAppl";
             fieldToSearch = "productFeatureGroupId";
@@ -84,18 +84,18 @@
             valueToSearch = (String) context.get("productId");
             orderBy = UtilMisc.toList("sequenceNum", "productFeatureApplTypeId", "productFeatureTypeId", "description");
         }
-        
+
         if (valueToSearch == null) {
             return ServiceUtil.returnError("This service requires a productId, a productFeatureGroupId, or a productFeatureCategoryId to run.");
         }
-        
+
         try {
             // get all product features in this feature category
             List<GenericValue> allFeatures = delegator.findByAnd(entityToSearch, UtilMisc.toMap(fieldToSearch, valueToSearch), orderBy);
-        
+
             if (entityToSearch.equals("ProductFeatureAndAppl") && productFeatureApplTypeId != null)
                 allFeatures = EntityUtil.filterByAnd(allFeatures, UtilMisc.toMap("productFeatureApplTypeId", productFeatureApplTypeId));
-                
+
             List<String> featureTypes = FastList.newInstance();
             Map<String, List<GenericValue>> featuresByType = new LinkedHashMap<String, List<GenericValue>>();
             for (GenericValue feature: allFeatures) {
@@ -120,7 +120,7 @@
         }
         return results;
     }
-    
+
     /*
      * Parameter: productId, productFeatureAppls (a List of ProductFeatureAndAppl entities of features applied to productId)
      * Result: variantProductIds: a List of productIds of variants with those features
@@ -132,11 +132,11 @@
         String productId = (String) context.get("productId");
         List<String> curProductFeatureAndAppls = UtilGenerics.checkList(context.get("productFeatureAppls"));
         List<String> existingVariantProductIds = FastList.newInstance();
-        
+
         try {
             /*
-             * get a list of all products which are associated with the current one as PRODUCT_VARIANT and for each one,
-             * see if it has every single feature in the list of productFeatureAppls as a STANDARD_FEATURE.  If so, then
+             * get a list of all products which are associated with the current one as PRODUCT_VARIANT and for each one,
+             * see if it has every single feature in the list of productFeatureAppls as a STANDARD_FEATURE.  If so, then
              * it qualifies and add it to the list of existingVariantProductIds.
              */
             List<GenericValue> productAssocs = EntityUtil.filterByDate(delegator.findByAnd("ProductAssoc", UtilMisc.toMap("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT")));
@@ -145,7 +145,7 @@
                 //for each associated product, if it has all standard features, display it's productId
                 boolean hasAllFeatures = true;
                 for (String productFeatureAndAppl: curProductFeatureAndAppls) {
-                    Map<String, String> findByMap = UtilMisc.toMap("productId", productAssoc.getString("productIdTo"),
+                    Map<String, String> findByMap = UtilMisc.toMap("productId", productAssoc.getString("productIdTo"),
                             "productFeatureId", productFeatureAndAppl,
                             "productFeatureApplTypeId", "STANDARD_FEATURE");
 
@@ -177,44 +177,44 @@
 
     /*
      * Parameter: productId (of the parent product which has SELECTABLE features)
-     * Result: featureCombinations, a List of Maps containing, for each possible variant of the productid:
+     * Result: featureCombinations, a List of Maps containing, for each possible variant of the productid:
      * {defaultVariantProductId: id of this variant; curProductFeatureAndAppls: features applied to this variant; existingVariantProductIds: List of productIds which are already variants with these features }
      */
     public static Map<String, Object> getVariantCombinations(DispatchContext dctx, Map<String, ? extends Object> context) {
         Map<String, Object> results = FastMap.newInstance();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        
+
         String productId = (String) context.get("productId");
-        
+
         try {
             Map<String, Object> featuresResults = dispatcher.runSync("getProductFeaturesByType", UtilMisc.toMap("productId", productId));
             Map<String, List<GenericValue>> features;
-            
+
             if (featuresResults.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)) {
                 features = UtilGenerics.checkMap(featuresResults.get("productFeaturesByType"));
             } else {
                 return ServiceUtil.returnError((String) featuresResults.get(ModelService.ERROR_MESSAGE_LIST));
             }
-            
+
             // need to keep 2 lists, oldCombinations and newCombinations, and keep swapping them after each looping.  Otherwise, you'll get a
             // concurrent modification exception
             List<Map<String, Object>> oldCombinations = FastList.newInstance();
-            
+
             // loop through each feature type
             for (Map.Entry<String, List<GenericValue>> entry: features.entrySet()) {
                 String currentFeatureType = entry.getKey();
                 List<GenericValue> currentFeatures = entry.getValue();
-                
+
                 List<Map<String, Object>> newCombinations = FastList.newInstance();
                 List<Map<String, Object>> combinations;
-                
+
                 // start with either existing combinations or from scratch
                 if (oldCombinations.size() > 0) {
                     combinations = oldCombinations;
                 } else {
                     combinations = FastList.newInstance();
                 }
-                
+
                 // in both cases, use each feature of current feature type's idCode and
                 // product feature and add it to the id code and product feature applications
                 // of the next variant.  just a matter of whether we're starting with an
@@ -264,11 +264,11 @@
                     oldCombinations = newCombinations; // save the newly expanded list as oldCombinations
                 }
             }
-            
+
             int defaultCodeCounter = 1;
             Set<String> defaultVariantProductIds = FastSet.newInstance(); // this map will contain the codes already used (as keys)
             defaultVariantProductIds.add(productId);
-            
+
             // now figure out which of these combinations already have productIds associated with them
             for (Map<String, Object> combination: oldCombinations) {
                 // Verify if the default code is already used, if so add a numeric suffix
@@ -287,11 +287,11 @@
             Debug.logError(ex, ex.getMessage(), module);
             return ServiceUtil.returnError(ex.getMessage());
         }
-        
+
         return results;
     }
 
-    /*
+    /*
      * Parameters: productCategoryId (String) and productFeatures (a List of ProductFeature GenericValues)
      * Result: products (a List of Product GenericValues)
      */
@@ -319,7 +319,7 @@
                 featuresByType.put(nextFeature.getString("productFeatureTypeId"), nextFeature.getString("productFeatureId"));
             }
 
-            List<GenericValue> products = FastList.newInstance();  // final list of variant products  
+            List<GenericValue> products = FastList.newInstance();  // final list of variant products
             for (GenericValue memberProduct: memberProducts) {
                 // find variants for each member product of the category
 
@@ -342,7 +342,7 @@
                 return ServiceUtil.returnError("No products which fit your requirements were found.");
             } else {
                 results = ServiceUtil.returnSuccess();
-                results.put("products", products);    
+                results.put("products", products);
             }
 
         } else {

Modified: ofbiz/trunk/applications/product/src/org/ofbiz/product/image/ScaleImage.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/product/src/org/ofbiz/product/image/ScaleImage.java?rev=757089&r1=757088&r2=757089&view=diff
==============================================================================
--- ofbiz/trunk/applications/product/src/org/ofbiz/product/image/ScaleImage.java (original)
+++ ofbiz/trunk/applications/product/src/org/ofbiz/product/image/ScaleImage.java Sat Mar 21 23:44:24 2009
@@ -1,251 +1,251 @@
-/*******************************************************************************
- * 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
+/*******************************************************************************
+ * 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.product.image;
-
-import java.awt.RenderingHints;
-import java.awt.geom.AffineTransform;
-import java.awt.image.AffineTransformOp;
-import java.awt.image.BufferedImage;
-import java.awt.image.ImagingOpException;
-import java.io.File;
-import java.io.IOException;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-import javax.imageio.ImageIO;
-
-import javolution.util.FastMap;
-
-import org.jdom.JDOMException;
-import org.ofbiz.base.util.Debug;
-import org.ofbiz.base.util.UtilMisc;
-import org.ofbiz.base.util.UtilProperties;
-import org.ofbiz.base.util.string.FlexibleStringExpander;
-import org.ofbiz.service.ServiceUtil;
-import org.ofbiz.common.image.ImageTransform;
+ * under the License.
+ *******************************************************************************/
+package org.ofbiz.product.image;
+
+import java.awt.RenderingHints;
+import java.awt.geom.AffineTransform;
+import java.awt.image.AffineTransformOp;
+import java.awt.image.BufferedImage;
+import java.awt.image.ImagingOpException;
+import java.io.File;
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+
+import javax.imageio.ImageIO;
+
+import javolution.util.FastMap;
+
+import org.jdom.JDOMException;
+import org.ofbiz.base.util.Debug;
+import org.ofbiz.base.util.UtilMisc;
+import org.ofbiz.base.util.UtilProperties;
+import org.ofbiz.base.util.string.FlexibleStringExpander;
+import org.ofbiz.service.ServiceUtil;
+import org.ofbiz.common.image.ImageTransform;
 
-/**
+/**
  * ScaleImage Class
- * <p>
- * Scale the original image into 4 different size Types (small, medium, large, detail)
- */
-public class ScaleImage {
-
-    public static final String module = ScaleImage.class.getName();
-    public static final String resource = "ProductErrorUiLabels";
-
-    public ScaleImage() {
-    }
-
-    /**
-     * scaleImageInAllSize
-     * <p>
-     * Scale the original image into all different size Types (small, medium, large, detail)
-     *
-     * @param   context                     Context
+ * <p>
+ * Scale the original image into 4 different size Types (small, medium, large, detail)
+ */
+public class ScaleImage {
+
+    public static final String module = ScaleImage.class.getName();
+    public static final String resource = "ProductErrorUiLabels";
+
+    public ScaleImage() {
+    }
+
+    /**
+     * 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"
+     * @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");
-        List<String> sizeTypeList = UtilMisc.toList("small", "medium", "large", "detail");
-        int index;
-        Map<String, Map<String, String>> imgPropertyMap = FastMap.newInstance();
-        BufferedImage bufImg, bufNewImg;
-        double imgHeight, imgWidth, scaleFactor;
-        AffineTransformOp op;
-        Map<String, String> imgUrlMap = FastMap.newInstance();
-        Map<String, Object> resultXMLMap = FastMap.newInstance();
-        Map<String, Object> resultBufImgMap = FastMap.newInstance();
-        Map<String, Object> resultScaleImgMap = FastMap.newInstance();
-        Map<String, Object> result = FastMap.newInstance();
-
-        /* ImageProperties.xml */
-        String imgPropertyFullPath = System.getProperty("ofbiz.home") + "/applications/product/config/ImageProperties.xml";
-        resultXMLMap.putAll((Map<String, Object>) ImageTransform.getXMLValue(imgPropertyFullPath, locale));
-        if (resultXMLMap.containsKey("responseMessage") && resultXMLMap.get("responseMessage").equals("success")) {
-            imgPropertyMap.putAll((Map<String, Map<String, String>>) resultXMLMap.get("xml"));
-        } else {
-            String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_parse", locale) + " : ImageProperties.xml";
-            Debug.logError(errMsg, module);
-            result.put("errorMessage", errMsg);
-            return result;
-        }
-
-        /* IMAGE */
-        // get Name and Extension
-        index = filenameToUse.lastIndexOf(".");
-        String imgName = filenameToUse.substring(0, index - 1);
-        String imgExtension = filenameToUse.substring(index + 1);
+     * @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");
+        List<String> sizeTypeList = UtilMisc.toList("small", "medium", "large", "detail");
+        int index;
+        Map<String, Map<String, String>> imgPropertyMap = FastMap.newInstance();
+        BufferedImage bufImg, bufNewImg;
+        double imgHeight, imgWidth, scaleFactor;
+        AffineTransformOp op;
+        Map<String, String> imgUrlMap = FastMap.newInstance();
+        Map<String, Object> resultXMLMap = FastMap.newInstance();
+        Map<String, Object> resultBufImgMap = FastMap.newInstance();
+        Map<String, Object> resultScaleImgMap = FastMap.newInstance();
+        Map<String, Object> result = FastMap.newInstance();
+
+        /* ImageProperties.xml */
+        String imgPropertyFullPath = System.getProperty("ofbiz.home") + "/applications/product/config/ImageProperties.xml";
+        resultXMLMap.putAll((Map<String, Object>) ImageTransform.getXMLValue(imgPropertyFullPath, locale));
+        if (resultXMLMap.containsKey("responseMessage") && resultXMLMap.get("responseMessage").equals("success")) {
+            imgPropertyMap.putAll((Map<String, Map<String, String>>) resultXMLMap.get("xml"));
+        } else {
+            String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_parse", locale) + " : ImageProperties.xml";
+            Debug.logError(errMsg, module);
+            result.put("errorMessage", 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
-        String mainFilenameFormat = UtilProperties.getPropertyValue("catalog", "image.filename.format");
-        String imageServerPath = FlexibleStringExpander.expandString(UtilProperties.getPropertyValue("catalog", "image.server.path"), context);
-        String imageUrlPrefix = UtilProperties.getPropertyValue("catalog", "image.url.prefix");
-
-        String id = null;
-        String type = null;
-        if (viewType.toLowerCase().contains("main")) {
-            type = "original";
-            id = imgName;
-        } else if (viewType.toLowerCase().contains("additional") && viewNumber != null && !viewNumber.equals("0")) {
-            type = "additional";
-            id = imgName + "_View_" + viewNumber;
-        } else {
-            return ServiceUtil.returnError("View Type : " + type + " is wrong");
-        }
-        FlexibleStringExpander mainFilenameExpander = FlexibleStringExpander.getInstance(mainFilenameFormat);
-        String fileLocation = mainFilenameExpander.expandString(UtilMisc.toMap("location", "products", "type", type, "id", filenameToUse));
-        String filePathPrefix = "";
-        if (fileLocation.lastIndexOf("/") != -1) {
-            filePathPrefix = fileLocation.substring(0, fileLocation.lastIndexOf("/") + 1); // adding 1 to include the trailing slash
-        }
-
-
-
-        /* get original BUFFERED IMAGE */
-        resultBufImgMap.putAll(ImageTransform.getBufferedImage(imageServerPath + "/" + filePathPrefix + filenameToUse, locale));
-
-        if (resultBufImgMap.containsKey("responseMessage") && resultBufImgMap.get("responseMessage").equals("success")) {
-            bufImg = (BufferedImage) resultBufImgMap.get("bufferedImage");
-
-            // get Dimensions    
-            imgHeight = (double) bufImg.getHeight();
-            imgWidth = (double) 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("errorMessage", errMsg);
-                return result;
-            }
-
-            // new Filename Format
-            FlexibleStringExpander addFilenameExpander = mainFilenameExpander;
-            if (viewType.toLowerCase().contains("additional")) {
-                String addFilenameFormat = UtilProperties.getPropertyValue("catalog", "image.filename.additionalviewsize.format");
-                addFilenameExpander = FlexibleStringExpander.getInstance(addFilenameFormat);
-            }
-
-            /* scale Image for each Size Type */
-            Iterator<String> sizeIter = sizeTypeList.iterator();
-            while (sizeIter.hasNext()) {
-                String sizeType = sizeIter.next();
-
-                resultScaleImgMap.putAll(ImageTransform.scaleImage(bufImg, imgHeight, imgWidth, imgPropertyMap, sizeType, locale));
-
-                if (resultScaleImgMap.containsKey("responseMessage") && resultScaleImgMap.get("responseMessage").equals("success")) {
-                    bufNewImg = (BufferedImage) resultScaleImgMap.get("bufferedImage");
-                    Double scaleFactorDb = (Double) resultScaleImgMap.get("scaleFactor");
-                    scaleFactor = scaleFactorDb.doubleValue();
-
-                    // define Interpolation
-                    Map<RenderingHints.Key, Object> rhMap = FastMap.newInstance();
-                        rhMap.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
-                        rhMap.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
-                        rhMap.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
-                        rhMap.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
-                        rhMap.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
-                        rhMap.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
-                        rhMap.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
-                        //rhMap.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
-                        rhMap.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
-                    RenderingHints rh = new RenderingHints(rhMap);
-
-                    /* IMAGE TRANFORMATION */
-                    AffineTransform tx = new AffineTransform();
-                    tx.scale(scaleFactor, scaleFactor);
-
-
-                    try {
-                        op = new AffineTransformOp(tx, rh);
-                    } catch (ImagingOpException e) {
-                        String errMsg = UtilProperties.getMessage(resource, "ScaleImage.transform_is_non_invertible", locale)  + e.toString();
-                        Debug.logError(errMsg, module);
-                        result.put("errorMessage", errMsg);
-                        return result;
-                    }
-
-                    // write the New Scaled Image
-                    String newFileLocation = null;
-                    if (viewType.toLowerCase().contains("main")) {
-                        newFileLocation = mainFilenameExpander.expandString(UtilMisc.toMap("location", "products", "type", sizeType, "id", id));
-                    } else if (viewType.toLowerCase().contains("additional")) {
-                        newFileLocation = addFilenameExpander.expandString(UtilMisc.toMap("location", "products", "viewtype", viewType, "sizetype", sizeType,"id", id));
-                    }
-                    String newFilePathPrefix = "";
-                    if (newFileLocation.lastIndexOf("/") != -1) {
-                        newFilePathPrefix = newFileLocation.substring(0, newFileLocation.lastIndexOf("/") + 1); // adding 1 to include the trailing slash
-                    }
-
-                    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(op.filter(bufImg, 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("errorMessage", 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("errorMessage", 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;
-
-        } else {
-            String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_scale_original_image", locale) + " : " + filenameToUse;
-            Debug.logError(errMsg, module);
-            result.put("errorMessage", errMsg);
-            return ServiceUtil.returnError(errMsg);
-        }
-    }
-}
+        String mainFilenameFormat = UtilProperties.getPropertyValue("catalog", "image.filename.format");
+        String imageServerPath = FlexibleStringExpander.expandString(UtilProperties.getPropertyValue("catalog", "image.server.path"), context);
+        String imageUrlPrefix = UtilProperties.getPropertyValue("catalog", "image.url.prefix");
+
+        String id = null;
+        String type = null;
+        if (viewType.toLowerCase().contains("main")) {
+            type = "original";
+            id = imgName;
+        } else if (viewType.toLowerCase().contains("additional") && viewNumber != null && !viewNumber.equals("0")) {
+            type = "additional";
+            id = imgName + "_View_" + viewNumber;
+        } else {
+            return ServiceUtil.returnError("View Type : " + type + " is wrong");
+        }
+        FlexibleStringExpander mainFilenameExpander = FlexibleStringExpander.getInstance(mainFilenameFormat);
+        String fileLocation = mainFilenameExpander.expandString(UtilMisc.toMap("location", "products", "type", type, "id", filenameToUse));
+        String filePathPrefix = "";
+        if (fileLocation.lastIndexOf("/") != -1) {
+            filePathPrefix = fileLocation.substring(0, fileLocation.lastIndexOf("/") + 1); // adding 1 to include the trailing slash
+        }
+
+
+
+        /* get original BUFFERED IMAGE */
+        resultBufImgMap.putAll(ImageTransform.getBufferedImage(imageServerPath + "/" + filePathPrefix + filenameToUse, locale));
+
+        if (resultBufImgMap.containsKey("responseMessage") && resultBufImgMap.get("responseMessage").equals("success")) {
+            bufImg = (BufferedImage) resultBufImgMap.get("bufferedImage");
+
+            // get Dimensions
+            imgHeight = (double) bufImg.getHeight();
+            imgWidth = (double) 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("errorMessage", errMsg);
+                return result;
+            }
+
+            // new Filename Format
+            FlexibleStringExpander addFilenameExpander = mainFilenameExpander;
+            if (viewType.toLowerCase().contains("additional")) {
+                String addFilenameFormat = UtilProperties.getPropertyValue("catalog", "image.filename.additionalviewsize.format");
+                addFilenameExpander = FlexibleStringExpander.getInstance(addFilenameFormat);
+            }
+
+            /* scale Image for each Size Type */
+            Iterator<String> sizeIter = sizeTypeList.iterator();
+            while (sizeIter.hasNext()) {
+                String sizeType = sizeIter.next();
+
+                resultScaleImgMap.putAll(ImageTransform.scaleImage(bufImg, imgHeight, imgWidth, imgPropertyMap, sizeType, locale));
+
+                if (resultScaleImgMap.containsKey("responseMessage") && resultScaleImgMap.get("responseMessage").equals("success")) {
+                    bufNewImg = (BufferedImage) resultScaleImgMap.get("bufferedImage");
+                    Double scaleFactorDb = (Double) resultScaleImgMap.get("scaleFactor");
+                    scaleFactor = scaleFactorDb.doubleValue();
+
+                    // define Interpolation
+                    Map<RenderingHints.Key, Object> rhMap = FastMap.newInstance();
+                        rhMap.put(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
+                        rhMap.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+                        rhMap.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
+                        rhMap.put(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
+                        rhMap.put(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
+                        rhMap.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
+                        rhMap.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
+                        //rhMap.put(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
+                        rhMap.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+                    RenderingHints rh = new RenderingHints(rhMap);
+
+                    /* IMAGE TRANFORMATION */
+                    AffineTransform tx = new AffineTransform();
+                    tx.scale(scaleFactor, scaleFactor);
+
+
+                    try {
+                        op = new AffineTransformOp(tx, rh);
+                    } catch (ImagingOpException e) {
+                        String errMsg = UtilProperties.getMessage(resource, "ScaleImage.transform_is_non_invertible", locale)  + e.toString();
+                        Debug.logError(errMsg, module);
+                        result.put("errorMessage", errMsg);
+                        return result;
+                    }
+
+                    // write the New Scaled Image
+                    String newFileLocation = null;
+                    if (viewType.toLowerCase().contains("main")) {
+                        newFileLocation = mainFilenameExpander.expandString(UtilMisc.toMap("location", "products", "type", sizeType, "id", id));
+                    } else if (viewType.toLowerCase().contains("additional")) {
+                        newFileLocation = addFilenameExpander.expandString(UtilMisc.toMap("location", "products", "viewtype", viewType, "sizetype", sizeType,"id", id));
+                    }
+                    String newFilePathPrefix = "";
+                    if (newFileLocation.lastIndexOf("/") != -1) {
+                        newFilePathPrefix = newFileLocation.substring(0, newFileLocation.lastIndexOf("/") + 1); // adding 1 to include the trailing slash
+                    }
+
+                    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(op.filter(bufImg, 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("errorMessage", 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("errorMessage", 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;
+
+        } else {
+            String errMsg = UtilProperties.getMessage(resource, "ScaleImage.unable_to_scale_original_image", locale) + " : " + filenameToUse;
+            Debug.logError(errMsg, module);
+            result.put("errorMessage", errMsg);
+            return ServiceUtil.returnError(errMsg);
+        }
+    }
+}

Modified: ofbiz/trunk/applications/product/src/org/ofbiz/product/inventory/InventoryServices.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/product/src/org/ofbiz/product/inventory/InventoryServices.java?rev=757089&r1=757088&r2=757089&view=diff
==============================================================================
--- ofbiz/trunk/applications/product/src/org/ofbiz/product/inventory/InventoryServices.java (original)
+++ ofbiz/trunk/applications/product/src/org/ofbiz/product/inventory/InventoryServices.java Sat Mar 21 23:44:24 2009
@@ -6,9 +6,9 @@
  * 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
@@ -53,55 +53,55 @@
  * Inventory Services
  */
 public class InventoryServices {
-    
+
     public final static String module = InventoryServices.class.getName();
-    
+
     public static final MathContext generalRounding = new MathContext(10);
 
     public static Map<String, Object> prepareInventoryTransfer(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         String inventoryItemId = (String) context.get("inventoryItemId");
-        BigDecimal xferQty = (BigDecimal) context.get("xferQty");  
+        BigDecimal xferQty = (BigDecimal) context.get("xferQty");
         GenericValue inventoryItem = null;
-        GenericValue newItem = null;        
-        GenericValue userLogin = (GenericValue) context.get("userLogin");        
-        
-        try {          
+        GenericValue newItem = null;
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
+
+        try {
             inventoryItem = delegator.findByPrimaryKey("InventoryItem", UtilMisc.toMap("inventoryItemId", inventoryItemId));
         } catch (GenericEntityException e) {
             return ServiceUtil.returnError("Inventory item lookup problem [" + e.getMessage() + "]");
         }
-        
+
         if (inventoryItem == null) {
             return ServiceUtil.returnError("Cannot locate inventory item.");
         }
 
         try {
             Map<String, Object> results = ServiceUtil.returnSuccess();
-            
+
             String inventoryType = inventoryItem.getString("inventoryItemTypeId");
             if (inventoryType.equals("NON_SERIAL_INV_ITEM")) {
                 BigDecimal atp = inventoryItem.getBigDecimal("availableToPromiseTotal");
                 BigDecimal qoh = inventoryItem.getBigDecimal("quantityOnHandTotal");
-                
+
                 if (atp == null) {
                     return ServiceUtil.returnError("The request transfer amount is not available, there is no available to promise on the Inventory Item with ID " + inventoryItem.getString("inventoryItemId"));
                 }
                 if (qoh == null) {
                     qoh = atp;
                 }
-                
+
                 // first make sure we have enough to cover the request transfer amount
                 if (xferQty.compareTo(atp) > 0) {
                     return ServiceUtil.returnError("The request transfer amount is not available, the available to promise [" + atp + "] is not sufficient for the desired transfer quantity [" + xferQty + "] on the Inventory Item with ID " + inventoryItem.getString("inventoryItemId"));
                 }
-                            
+
                 /*
                  * atp < qoh - split and save the qoh - atp
                  * xferQty < atp - split and save atp - xferQty
                  * atp < qoh && xferQty < atp - split and save qoh - atp + atp - xferQty
                  */
-    
+
                 // at this point we have already made sure that the xferQty is less than or equals to the atp, so if less that just create a new inventory record for the quantity to be moved
                 // NOTE: atp should always be <= qoh, so if xfer < atp, then xfer < qoh, so no need to check/handle that
                 // however, if atp < qoh && atp == xferQty, then we still need to split; oh, but no need to check atp == xferQty in the second part because if it isn't greater and isn't less, then it is equal
@@ -115,17 +115,17 @@
                     newItem = GenericValue.create(inventoryItem);
                     newItem.set("availableToPromiseTotal", BigDecimal.ZERO);
                     newItem.set("quantityOnHandTotal", BigDecimal.ZERO);
-                    
+
                     delegator.createSetNextSeqId(newItem);
-                    
+
                     results.put("inventoryItemId", newItem.get("inventoryItemId"));
-    
+
                     // TODO: how do we get this here: "inventoryTransferId", inventoryTransferId
                     Map<String, Object> createNewDetailMap = UtilMisc.toMap("availableToPromiseDiff", xferQty, "quantityOnHandDiff", xferQty,
                             "inventoryItemId", newItem.get("inventoryItemId"), "userLogin", userLogin);
                     Map<String, Object> createUpdateDetailMap = UtilMisc.toMap("availableToPromiseDiff", negXferQty, "quantityOnHandDiff", negXferQty,
                             "inventoryItemId", inventoryItem.get("inventoryItemId"), "userLogin", userLogin);
-                    
+
                     try {
                         Map<String, Object> resultNew = dctx.getDispatcher().runSync("createInventoryItemDetail", createNewDetailMap);
                         if (ServiceUtil.isError(resultNew)) {
@@ -145,8 +145,8 @@
                 if (!"INV_AVAILABLE".equals(inventoryItem.getString("statusId"))) {
                     return ServiceUtil.returnError("Serialized inventory is not available for transfer.");
                 }
-            }      
-                    
+            }
+
             // setup values so that no one will grab the inventory during the move
             // if newItem is not null, it is the item to be moved, otherwise the original inventoryItem is the one to be moved
             if (inventoryType.equals("NON_SERIAL_INV_ITEM")) {
@@ -156,7 +156,7 @@
                 inventoryItemToClear.refresh();
                 BigDecimal atp = inventoryItemToClear.get("availableToPromiseTotal") == null ? BigDecimal.ZERO : inventoryItemToClear.getBigDecimal("availableToPromiseTotal");
                 if (atp.compareTo(BigDecimal.ZERO) != 0) {
-                    Map<String, Object> createDetailMap = UtilMisc.toMap("availableToPromiseDiff", atp.negate(),
+                    Map<String, Object> createDetailMap = UtilMisc.toMap("availableToPromiseDiff", atp.negate(),
                             "inventoryItemId", inventoryItemToClear.get("inventoryItemId"), "userLogin", userLogin);
                     try {
                         Map<String, Object> result = dctx.getDispatcher().runSync("createInventoryItemDetail", createDetailMap);
@@ -181,46 +181,46 @@
                     results.put("inventoryItemId", inventoryItem.get("inventoryItemId"));
               }
             }
-                                    
-            return results;    
+
+            return results;
         } catch (GenericEntityException e) {
             return ServiceUtil.returnError("Inventory store/create problem [" + e.getMessage() + "]");
-        }                                                                                                  
+        }
     }
-    
+
     public static Map<String, Object> completeInventoryTransfer(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         String inventoryTransferId = (String) context.get("inventoryTransferId");
         GenericValue inventoryTransfer = null;
         GenericValue inventoryItem = null;
         GenericValue destinationFacility = null;
-        GenericValue userLogin = (GenericValue) context.get("userLogin");        
-        
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
+
         try {
-            inventoryTransfer = delegator.findByPrimaryKey("InventoryTransfer",
+            inventoryTransfer = delegator.findByPrimaryKey("InventoryTransfer",
                     UtilMisc.toMap("inventoryTransferId", inventoryTransferId));
             inventoryItem = inventoryTransfer.getRelatedOne("InventoryItem");
             destinationFacility = inventoryTransfer.getRelatedOne("ToFacility");
         } catch (GenericEntityException e) {
             return ServiceUtil.returnError("Inventory Item/Transfer lookup problem [" + e.getMessage() + "]");
         }
-        
+
         if (inventoryTransfer == null || inventoryItem == null) {
             return ServiceUtil.returnError("ERROR: Lookup of InventoryTransfer and/or InventoryItem failed!");
         }
-            
+
         String inventoryType = inventoryItem.getString("inventoryItemTypeId");
-        
-        // set the fields on the transfer record            
+
+        // set the fields on the transfer record
         if (inventoryTransfer.get("receiveDate") == null) {
             inventoryTransfer.set("receiveDate", UtilDateTime.nowTimestamp());
         }
-            
-        if (inventoryType.equals("NON_SERIAL_INV_ITEM")) {
+
+        if (inventoryType.equals("NON_SERIAL_INV_ITEM")) {
             // add an adjusting InventoryItemDetail so set ATP back to QOH: ATP = ATP + (QOH - ATP), diff = QOH - ATP
             BigDecimal atp = inventoryItem.get("availableToPromiseTotal") == null ? BigDecimal.ZERO : inventoryItem.getBigDecimal("availableToPromiseTotal");
             BigDecimal qoh = inventoryItem.get("quantityOnHandTotal") == null ? BigDecimal.ZERO : inventoryItem.getBigDecimal("quantityOnHandTotal");
-            Map<String, Object> createDetailMap = UtilMisc.toMap("availableToPromiseDiff", qoh.subtract(atp),
+            Map<String, Object> createDetailMap = UtilMisc.toMap("availableToPromiseDiff", qoh.subtract(atp),
                     "inventoryItemId", inventoryItem.get("inventoryItemId"), "userLogin", userLogin);
             try {
                 Map<String, Object> result = dctx.getDispatcher().runSync("createInventoryItemDetail", createDetailMap);
@@ -249,8 +249,8 @@
             updateInventoryItemMap.put("statusId", "INV_AVAILABLE");
         }
 
-        // if the destination facility's owner is different
-        // from the inventory item's ownwer,
+        // if the destination facility's owner is different
+        // from the inventory item's ownwer,
         // the inventory item is assigned to the new owner.
         if (destinationFacility != null && destinationFacility.get("ownerPartyId") != null) {
             String fromPartyId = inventoryItem.getString("ownerPartyId");
@@ -270,17 +270,17 @@
 
         // set the inventory transfer record to complete
         inventoryTransfer.set("statusId", "IXF_COMPLETE");
-        
+
         // store the entities
         try {
             inventoryTransfer.store();
         } catch (GenericEntityException e) {
             return ServiceUtil.returnError("Inventory store problem [" + e.getMessage() + "]");
         }
-        
+
         return ServiceUtil.returnSuccess();
-    }    
-    
+    }
+
     public static Map<String, Object> cancelInventoryTransfer(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         String inventoryTransferId = (String) context.get("inventoryTransferId");
@@ -302,15 +302,15 @@
         if (inventoryTransfer == null || inventoryItem == null) {
             return ServiceUtil.returnError("ERROR: Lookup of InventoryTransfer and/or InventoryItem failed!");
         }
-            
+
         String inventoryType = inventoryItem.getString("inventoryItemTypeId");
-        
+
         // re-set the fields on the item
         if (inventoryType.equals("NON_SERIAL_INV_ITEM")) {
             // add an adjusting InventoryItemDetail so set ATP back to QOH: ATP = ATP + (QOH - ATP), diff = QOH - ATP
             BigDecimal atp = inventoryItem.get("availableToPromiseTotal") == null ? BigDecimal.ZERO : inventoryItem.getBigDecimal("availableToPromiseTotal");
             BigDecimal qoh = inventoryItem.get("quantityOnHandTotal") == null ? BigDecimal.ZERO : inventoryItem.getBigDecimal("quantityOnHandTotal");
-            Map<String, Object> createDetailMap = UtilMisc.toMap("availableToPromiseDiff", qoh.subtract(atp),
+            Map<String, Object> createDetailMap = UtilMisc.toMap("availableToPromiseDiff", qoh.subtract(atp),
                                                  "inventoryItemId", inventoryItem.get("inventoryItemId"),
                                                  "userLogin", userLogin);
             try {
@@ -348,7 +348,7 @@
     public static Map<String, Object> checkInventoryAvailability(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin = (GenericValue) context.get("userLogin");        
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
 
         /* TODO: NOTE: This method has been updated, but testing requires many eyes. See http://jira.undersunconsulting.com/browse/OFBIZ-662
         boolean skipThisNeedsUpdating = true;
@@ -357,10 +357,10 @@
             return ServiceUtil.returnSuccess();
         }
         */
-        
+
         Map<String, Map<String, Timestamp>> ordersToUpdate = FastMap.newInstance();
-        Map<String, Map<String, Timestamp>> ordersToCancel = FastMap.newInstance();      
-        
+        Map<String, Map<String, Timestamp>> ordersToCancel = FastMap.newInstance();
+
         // find all inventory items w/ a negative ATP
         List<GenericValue> inventoryItems = null;
         try {
@@ -370,14 +370,14 @@
             Debug.logError(e, "Trouble getting inventory items", module);
             return ServiceUtil.returnError("Problem getting InventoryItem records");
         }
-                        
+
         if (inventoryItems == null) {
             Debug.logInfo("No items out of stock; no backorders to worry about", module);
             return ServiceUtil.returnSuccess();
         }
-        
+
         Debug.log("OOS Inventory Items: " + inventoryItems.size(), module);
-        
+
         for (GenericValue inventoryItem: inventoryItems) {
             // get the incomming shipment information for the item
             List<GenericValue> shipmentAndItems = null;
@@ -389,12 +389,12 @@
                 exprs.add(EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "SHIPMENT_CANCELLED"));
 
                 EntityConditionList<EntityExpr> ecl = EntityCondition.makeCondition(exprs, EntityOperator.AND);
-                shipmentAndItems = delegator.findList("ShipmentAndItem", ecl, null, UtilMisc.toList("estimatedArrivalDate"), null, false);  
+                shipmentAndItems = delegator.findList("ShipmentAndItem", ecl, null, UtilMisc.toList("estimatedArrivalDate"), null, false);
             } catch (GenericEntityException e) {
                 Debug.logError(e, "Problem getting ShipmentAndItem records", module);
                 return ServiceUtil.returnError("Problem getting ShipmentAndItem records");
             }
-            
+
             // get the reservations in order of newest first
             List<GenericValue> reservations = null;
             try {
@@ -403,17 +403,17 @@
                 Debug.logError(e, "Problem getting related reservations", module);
                 return ServiceUtil.returnError("Problem getting related reservations");
             }
-            
+
             if (reservations == null) {
                 Debug.logWarning("No outstanding reservations for this inventory item, why is it negative then?", module);
                 continue;
             }
-            
+
             Debug.log("Reservations for item: " + reservations.size(), module);
-            
+
             // available at the time of order
             BigDecimal availableBeforeReserved = inventoryItem.getBigDecimal("availableToPromiseTotal");
-            
+
             // go through all the reservations in order
             for (GenericValue reservation: reservations) {
                 String orderId = reservation.getString("orderId");
@@ -429,9 +429,9 @@
                         actualPromiseDate = reservation.getTimestamp("reservedDatetime");
                     }
                 }
-                
+
                 Debug.log("Promised Date: " + actualPromiseDate, module);
-                                                              
+
                 // find the next possible ship date
                 Timestamp nextShipDate = null;
                 BigDecimal availableAtTime = BigDecimal.ZERO;
@@ -442,25 +442,25 @@
                         break;
                     }
                 }
-                
+
                 Debug.log("Next Ship Date: " + nextShipDate, module);
-                                                
+
                 // create a modified promise date (promise date - 1 day)
                 Calendar pCal = Calendar.getInstance();
                 pCal.setTimeInMillis(actualPromiseDate.getTime());
                 pCal.add(Calendar.DAY_OF_YEAR, -1);
                 Timestamp modifiedPromisedDate = new Timestamp(pCal.getTimeInMillis());
                 Timestamp now = UtilDateTime.nowTimestamp();
-                
+
                 Debug.log("Promised Date + 1: " + modifiedPromisedDate, module);
                 Debug.log("Now: " + now, module);
-                            
+
                 // check the promised date vs the next ship date
                 if (nextShipDate == null || nextShipDate.after(actualPromiseDate)) {
                     if (nextShipDate == null && modifiedPromisedDate.after(now)) {
                         // do nothing; we are okay to assume it will be shipped on time
                         Debug.log("No ship date known yet, but promised date hasn't approached, assuming it will be here on time", module);
-                    } else {                    
+                    } else {
                         // we cannot ship by the promised date; need to notify the customer
                         Debug.log("We won't ship on time, getting notification info", module);
                         Map<String, Timestamp> notifyItems = ordersToUpdate.get(orderId);
@@ -469,15 +469,15 @@
                         }
                         notifyItems.put(orderItemSeqId, nextShipDate);
                         ordersToUpdate.put(orderId, notifyItems);
-                        
+
                         // need to know if nextShipDate is more then 30 days after promised
                         Calendar sCal = Calendar.getInstance();
                         sCal.setTimeInMillis(actualPromiseDate.getTime());
                         sCal.add(Calendar.DAY_OF_YEAR, 30);
                         Timestamp farPastPromised = new Timestamp(sCal.getTimeInMillis());
-                        
+
                         // check to see if this is >30 days or second run, if so flag to cancel
-                        boolean needToCancel = false;                      
+                        boolean needToCancel = false;
                         if (nextShipDate == null || nextShipDate.after(farPastPromised)) {
                             // we cannot ship until >30 days after promised; using cancel rule
                             Debug.log("Ship date is >30 past the promised date", module);
@@ -486,9 +486,9 @@
                             // this is the second notification; using cancel rule
                             needToCancel = true;
                         }
-                        
+
                         // add the info to the cancel map if we need to schedule a cancel
-                        if (needToCancel) {                        
+                        if (needToCancel) {
                             // queue the item to be cancelled
                             Debug.log("Flagging the item to auto-cancel", module);
                             Map<String, Timestamp> cancelItems = ordersToCancel.get(orderId);
@@ -498,7 +498,7 @@
                             cancelItems.put(orderItemSeqId, farPastPromised);
                             ordersToCancel.put(orderId, cancelItems);
                         }
-                        
+
                         // store the updated promiseDate as the nextShipDate
                         try {
                             reservation.set("currentPromisedDate", nextShipDate);
@@ -506,14 +506,14 @@
                         } catch (GenericEntityException e) {
                             Debug.logError(e, "Problem storing reservation : " + reservation, module);
                         }
-                    }                    
+                    }
                 }
-                                
+
                 // subtract our qty from reserved to get the next value
                 availableBeforeReserved = availableBeforeReserved.subtract(reservation.getBigDecimal("quantity"));
             }
         }
-              
+
         // all items to cancel will also be in the notify list so start with that
         List<String> ordersToNotify = FastList.newInstance();
         for (Map.Entry<String, Map<String, Timestamp>> entry: ordersToUpdate.entrySet()) {
@@ -522,7 +522,7 @@
             Map<String, Timestamp> cancelItems = ordersToCancel.get(orderId);
             boolean cancelAll = false;
             Timestamp cancelAllTime = null;
-            
+
             List<GenericValue> orderItemShipGroups = null;
             try {
                 orderItemShipGroups= delegator.findByAnd("OrderItemShipGroup",
@@ -530,18 +530,18 @@
             } catch (GenericEntityException e) {
                 Debug.logError(e, "Cannot get OrderItemShipGroups from orderId" + orderId, module);
             }
-            
+
             for (GenericValue orderItemShipGroup: orderItemShipGroups) {
                 List<GenericValue> orderItems = FastList.newInstance();
                 List<GenericValue> orderItemShipGroupAssoc = null;
-                try {                    
+                try {
                     orderItemShipGroupAssoc =
                         delegator.findByAnd("OrderItemShipGroupAssoc",
                                 UtilMisc.toMap("shipGroupSeqId",
                                         orderItemShipGroup.get("shipGroupSeqId"),
                                         "orderId",
                                         orderId));
-                    
+
                     for (GenericValue assoc: orderItemShipGroupAssoc) {
                         GenericValue orderItem = assoc.getRelatedOne("OrderItem");
                         if (orderItem != null) {
@@ -551,41 +551,41 @@
                 } catch (GenericEntityException e) {
                      Debug.logError(e, "Problem fetching OrderItemShipGroupAssoc", module);
                 }
-                
-    
+
+
                 /* Check the split preference. */
                 boolean maySplit = false;
                 if (orderItemShipGroup != null && orderItemShipGroup.get("maySplit") != null) {
                     maySplit = orderItemShipGroup.getBoolean("maySplit").booleanValue();
                 }
-                
+
                 /* Figure out if we must cancel all items. */
                 if (!maySplit && cancelItems != null) {
                     cancelAll = true;
                     Set<String> cancelSet = cancelItems.keySet();
                     cancelAllTime = cancelItems.get(cancelSet.iterator().next());
                 }
-                
+
                 // if there are none to cancel just create an empty map
                 if (cancelItems == null) {
                     cancelItems = FastMap.newInstance();
                 }
-                
-                if (orderItems != null) {            
+
+                if (orderItems != null) {
                     List<GenericValue> toBeStored = FastList.newInstance();
                     for (GenericValue orderItem: orderItems) {
                         String orderItemSeqId = orderItem.getString("orderItemSeqId");
                         Timestamp shipDate = (Timestamp) backOrderedItems.get(orderItemSeqId);
                         Timestamp cancelDate = (Timestamp) cancelItems.get(orderItemSeqId);
                         Timestamp currentCancelDate = orderItem.getTimestamp("autoCancelDate");
-                        
+
                         Debug.logError("OI: " + orderId + " SEQID: "+ orderItemSeqId + " cancelAll: " + cancelAll + " cancelDate: " + cancelDate, module);
                         if (backOrderedItems.containsKey(orderItemSeqId)) {
                             orderItem.set("estimatedShipDate", shipDate);
-                            
-                            if (currentCancelDate == null) {                        
+
+                            if (currentCancelDate == null) {
                                 if (cancelAll || cancelDate != null) {
-                                    if (orderItem.get("dontCancelSetUserLogin") == null && orderItem.get("dontCancelSetDate") == null) {                            
+                                    if (orderItem.get("dontCancelSetUserLogin") == null && orderItem.get("dontCancelSetDate") == null) {
                                         if (cancelAllTime != null) {
                                             orderItem.set("autoCancelDate", cancelAllTime);
                                         } else {
@@ -594,9 +594,9 @@
                                     }
                                 }
                                 // only notify orders which have not already sent the final notice
-                                ordersToNotify.add(orderId);                        
+                                ordersToNotify.add(orderId);
                             }
-                            toBeStored.add(orderItem);                        
+                            toBeStored.add(orderItem);
                         }
                     }
                     if (toBeStored.size() > 0) {
@@ -607,12 +607,12 @@
                         }
                     }
                 }
-                
-                
-            }            
+
+
+            }
         }
-        
-        // send off a notification for each order        
+
+        // send off a notification for each order
         for (String orderId: ordersToNotify) {
             try {
                 dispatcher.runAsync("sendOrderBackorderNotification", UtilMisc.<String, Object>toMap("orderId", orderId, "userLogin", userLogin));
@@ -620,40 +620,40 @@
                 Debug.logError(e, "Problems sending off the notification", module);
                 continue;
             }
-        }        
-        
+        }
+
         return ServiceUtil.returnSuccess();
     }
-    
+
     /**
      * Get Inventory Available for a Product based on the list of associated products.  The final ATP and QOH will
-     * be the minimum of all the associated products' inventory divided by their ProductAssoc.quantity
+     * be the minimum of all the associated products' inventory divided by their ProductAssoc.quantity
      * */
     public static Map<String, Object> getProductInventoryAvailableFromAssocProducts(DispatchContext dctx, Map<String, ? extends Object> context) {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         List<GenericValue> productAssocList = UtilGenerics.checkList(context.get("assocProducts"));
         String facilityId = (String)context.get("facilityId");
         String statusId = (String)context.get("statusId");
-        
+
         BigDecimal availableToPromiseTotal = BigDecimal.ZERO;
         BigDecimal quantityOnHandTotal = BigDecimal.ZERO;
-        
+
         if (UtilValidate.isNotEmpty(productAssocList)) {
             // minimum QOH and ATP encountered
             BigDecimal minQuantityOnHandTotal = null;
             BigDecimal minAvailableToPromiseTotal = null;
-          
-           // loop through each associated product.  
+
+           // loop through each associated product.
            for (GenericValue productAssoc: productAssocList) {
                String productIdTo = productAssoc.getString("productIdTo");
                BigDecimal assocQuantity = productAssoc.getBigDecimal("quantity");
-              
+
                // if there is no quantity for the associated product in ProductAssoc entity, default it to 1.0
                if (assocQuantity == null) {
                    Debug.logWarning("ProductAssoc from [" + productAssoc.getString("productId") + "] to [" + productAssoc.getString("productIdTo") + "] has no quantity, assuming 1.0", module);
                    assocQuantity = BigDecimal.ONE;
                }
-              
+
                // figure out the inventory available for this associated product
                Map<String, Object> resultOutput = null;
                try {
@@ -668,7 +668,7 @@
                   Debug.logError(e, "Problems getting inventory available by facility", module);
                   return ServiceUtil.returnError(e.getMessage());
                }
-              
+
                // Figure out what the QOH and ATP inventory would be with this associated product
                BigDecimal currentQuantityOnHandTotal = (BigDecimal) resultOutput.get("quantityOnHandTotal");
                BigDecimal currentAvailableToPromiseTotal = (BigDecimal) resultOutput.get("availableToPromiseTotal");
@@ -682,9 +682,9 @@
                if (minAvailableToPromiseTotal == null || tmpAvailableToPromiseTotal.compareTo(minAvailableToPromiseTotal) < 0) {
                    minAvailableToPromiseTotal = tmpAvailableToPromiseTotal;
                }
-            
+
                if (Debug.verboseOn()) {
-                   Debug.logVerbose("productIdTo = " + productIdTo + " assocQuantity = " + assocQuantity + "current QOH " + currentQuantityOnHandTotal +
+                   Debug.logVerbose("productIdTo = " + productIdTo + " assocQuantity = " + assocQuantity + "current QOH " + currentQuantityOnHandTotal +
                         "currentATP = " + currentAvailableToPromiseTotal + " minQOH = " + minQuantityOnHandTotal + " minATP = " + minAvailableToPromiseTotal, module);
                }
            }
@@ -692,7 +692,7 @@
           quantityOnHandTotal = minQuantityOnHandTotal;
           availableToPromiseTotal = minAvailableToPromiseTotal;
         }
-        
+
         Map<String, Object> result = ServiceUtil.returnSuccess();
         result.put("availableToPromiseTotal", availableToPromiseTotal);
         result.put("quantityOnHandTotal", quantityOnHandTotal);
@@ -715,7 +715,7 @@
         List<GenericValue> facilities = null;
         try {
             if (facilityId != null) {
-                facilities = delegator.findByAnd("Facility", UtilMisc.toMap("facilityId", facilityId));
+                facilities = delegator.findByAnd("Facility", UtilMisc.toMap("facilityId", facilityId));
             } else {
                 facilities = delegator.findList("Facility", null, null, null, null, false);
             }
@@ -787,7 +787,7 @@
         results.put("mktgPkgQOHMap", mktgPkgQohMap);
         return results;
     }
-    
+
 
     public static Map<String, Object> getProductInventoryAndFacilitySummary(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
@@ -842,15 +842,15 @@
             availableToPromiseTotal = (BigDecimal)resultOutput.get("availableToPromiseTotal");
         }
         BigDecimal offsetATPQtyAvailable = availableToPromiseTotal.subtract(minimumStock);
-    
+
         BigDecimal quantityOnOrder = InventoryWorker.getOutstandingPurchasedQuantity(productId, delegator);
         result.put("totalQuantityOnHand", resultOutput.get("quantityOnHandTotal").toString());
         result.put("totalAvailableToPromise", resultOutput.get("availableToPromiseTotal").toString());
         result.put("quantityOnOrder", quantityOnOrder);
-    
+
         result.put("offsetQOHQtyAvailable", offsetQOHQtyAvailable);
         result.put("offsetATPQtyAvailable", offsetATPQtyAvailable);
-    
+
         List<GenericValue> productPrices = null;
         try {
             productPrices = delegator.findByAndCache("ProductPrice", UtilMisc.toMap("productId",productId), UtilMisc.toList("-fromDate"));
@@ -872,11 +872,11 @@
                 result.put("wholeSalePrice", onePrice.getBigDecimal("price"));
             }
         }
-    
+
         DynamicViewEntity salesUsageViewEntity = new DynamicViewEntity();
         DynamicViewEntity productionUsageViewEntity = new DynamicViewEntity();
         if (! UtilValidate.isEmpty(checkTime)) {
-    
+
             // Construct a dynamic view entity to search against for sales usage quantities
             salesUsageViewEntity.addMemberEntity("OI", "OrderItem");
             salesUsageViewEntity.addMemberEntity("OH", "OrderHeader");
@@ -892,7 +892,7 @@
             salesUsageViewEntity.addAlias("ItIss", "inventoryItemId");
             salesUsageViewEntity.addAlias("ItIss", "quantity");
             salesUsageViewEntity.addAlias("InvIt", "facilityId");
-        
+
             // Construct a dynamic view entity to search against for production usage quantities
             productionUsageViewEntity.addMemberEntity("WEIA", "WorkEffortInventoryAssign");
             productionUsageViewEntity.addMemberEntity("WE", "WorkEffort");
@@ -907,11 +907,11 @@
 
         }
         if (! UtilValidate.isEmpty(checkTime)) {
-            
+
             // Make a query against the sales usage view entity
             EntityListIterator salesUsageIt = null;
             try {
-                salesUsageIt = delegator.findListIteratorByCondition(salesUsageViewEntity,
+                salesUsageIt = delegator.findListIteratorByCondition(salesUsageViewEntity,
                         EntityCondition.makeCondition(
                             UtilMisc.toList(
                                 EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId),
@@ -926,7 +926,7 @@
                 // TODO Auto-generated catch block
                 e2.printStackTrace();
             }
-    
+
             // Sum the sales usage quantities found
             BigDecimal salesUsageQuantity = BigDecimal.ZERO;
             GenericValue salesUsageItem = null;
@@ -945,11 +945,11 @@
                 // TODO Auto-generated catch block
                 e2.printStackTrace();
             }
-    
+
             // Make a query against the production usage view entity
             EntityListIterator productionUsageIt = null;
             try {
-                productionUsageIt = delegator.findListIteratorByCondition(productionUsageViewEntity,
+                productionUsageIt = delegator.findListIteratorByCondition(productionUsageViewEntity,
                         EntityCondition.makeCondition(
                             UtilMisc.toList(
                                 EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId),
@@ -963,7 +963,7 @@
                 // TODO Auto-generated catch block
                 e1.printStackTrace();
             }
-    
+
             // Sum the production usage quantities found
             BigDecimal productionUsageQuantity = BigDecimal.ZERO;
             GenericValue productionUsageItem = null;
@@ -982,7 +982,7 @@
                 // TODO Auto-generated catch block
                 e.printStackTrace();
             }
-    
+
             result.put("usageQuantity", salesUsageQuantity.add(productionUsageQuantity));
 
         }

Modified: ofbiz/trunk/applications/product/src/org/ofbiz/product/inventory/InventoryWorker.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/product/src/org/ofbiz/product/inventory/InventoryWorker.java?rev=757089&r1=757088&r2=757089&view=diff
==============================================================================
--- ofbiz/trunk/applications/product/src/org/ofbiz/product/inventory/InventoryWorker.java (original)
+++ ofbiz/trunk/applications/product/src/org/ofbiz/product/inventory/InventoryWorker.java Sat Mar 21 23:44:24 2009
@@ -6,9 +6,9 @@
  * 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
@@ -38,7 +38,7 @@
 import org.ofbiz.entity.condition.EntityOperator;
 
 public class InventoryWorker {
-    
+
     public final static String module = InventoryWorker.class.getName();
 
     /**
@@ -57,7 +57,7 @@
                     EntityCondition.makeCondition("itemStatusId", EntityOperator.NOT_EQUAL, "ITEM_REJECTED"));
             purchaseOrderConditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, "PURCHASE_ORDER"));
             purchaseOrderConditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId));
-            List<GenericValue> purchaseOrders = delegator.findList("OrderHeaderAndItems", EntityCondition.makeCondition(purchaseOrderConditions, EntityOperator.AND),
+            List<GenericValue> purchaseOrders = delegator.findList("OrderHeaderAndItems", EntityCondition.makeCondition(purchaseOrderConditions, EntityOperator.AND),
                     null, UtilMisc.toList("estimatedDeliveryDate DESC", "orderDate"), null, false);
             return purchaseOrders;
         } catch (GenericEntityException ex) {
@@ -65,7 +65,7 @@
             return null;
         }
     }
-    
+
     /**
      * Finds the net outstanding ordered quantity for a productId, netting quantity on outstanding purchase orders against cancelQuantity
      * @param productId
@@ -112,7 +112,7 @@
                 EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_COMPLETED"),
                 EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_REJECTED"),
                 EntityCondition.makeCondition("orderStatusId", EntityOperator.NOT_EQUAL, "ORDER_CANCELLED")
-                );    
+                );
         if (productIds.size() > 0) {
             condList.add(EntityCondition.makeCondition("productId", EntityOperator.IN, productIds));
         }
@@ -142,4 +142,4 @@
     public static Map<String, BigDecimal> getOutstandingProductQuantitiesForPurchaseOrders(Collection<String> productIds, GenericDelegator delegator) {
         return getOutstandingProductQuantities(productIds, "PURCHASE_ORDER", delegator);
     }
-}    
+}