com.toughland.helpmechoose.common.Helper.java Source code

Java tutorial

Introduction

Here is the source code for com.toughland.helpmechoose.common.Helper.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.toughland.helpmechoose.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.toughland.helpmechoose.model.SearchProduct;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author ricardo
 */
public class Helper {

    ConfigProperty config = new ConfigProperty();

    public Map<String, Object> getBestBuyMap(RequestPackage requestPackage) {
        return getBestBuyMap(requestPackage, null);
    }

    public List<SearchProduct> getProductsDetails(List<String> skus) {

        List<SearchProduct> result = new ArrayList<>();

        String searchQuery = "";
        for (int i = 0; i < skus.size(); i++) {
            searchQuery += skus.get(i) + ((i < (skus.size() - 1)) ? "|sku=" : "");
        }
        RequestPackage requestPackage = new RequestPackage();
        requestPackage.setUri("products(sku=" + searchQuery + ")");
        requestPackage.setParam("show", "sku,name,image,salePrice,shortDescriptionHtml");
        requestPackage.setParam("pageSize", "3");
        requestPackage.setParam("page", "1");

        Map<String, Object> map = getBestBuyMap(requestPackage);

        // parse result
        List<Map<String, Object>> products = (List<Map<String, Object>>) map.get("products");
        for (Map<String, Object> product : products) {
            SearchProduct searchProduct = new SearchProduct();
            searchProduct.setImage(product.get("image").toString());
            searchProduct.setName(product.get("name").toString());
            if (product.get("shortDescriptionHtml") != null) {
                searchProduct.setShortDescription(product.get("shortDescriptionHtml").toString());
            }
            searchProduct.setSku(product.get("sku").toString());
            searchProduct.setSalePrice(Double.parseDouble(product.get("salePrice").toString()));
            result.add(searchProduct);
        }
        return result;
    }

    public Map<String, Object> getBestBuyMap(RequestPackage requestPackage, String fullUrl) {
        Map<String, Object> map = null;
        try {
            URL url = new URL("http://api.remix.bestbuy.com/v1/" + requestPackage.getUri() + "?"
                    + requestPackage.getEncodedParams() + "&format=json&apiKey="
                    + config.getPropValue("bestBuyApiKey"));

            if (fullUrl != null) {
                url = new URL(fullUrl + "?apiKey=" + config.getPropValue("bestBuyApiKey"));
            }

            ObjectMapper mapper = new ObjectMapper();
            map = mapper.readValue(url, Map.class);
        } catch (IOException ex) {
            Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
        }
        return map;
    }

    public String treatText(String text) {
        text = text.replace(" ", "%20");
        return text;
    }

    public String getBlendedImage(List<String> urls, Integer userId, HttpServletRequest request) {
        // TODO: add app logo
        urls.add("http://java-helpmechoose.rhcloud.com/images/help.png");

        String path = request.getServletContext().getRealPath("/") + "images\\temp\\";
        List<String> fileNames = new ArrayList<>();
        try {

            int count = 1;
            for (String item : urls) {
                URL url = new URL(item);
                InputStream in = new BufferedInputStream(url.openStream());
                OutputStream out = new BufferedOutputStream(
                        new FileOutputStream(path + userId.toString() + "_" + count + ".jpg"));
                for (int i; (i = in.read()) != -1;) {
                    out.write(i);
                }
                in.close();
                out.close();

                fileNames.add(path + userId.toString() + "_" + count + ".jpg");

                count++;
            }
        } catch (Exception e) {
            Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, e);
        }

        return getUrl(request) + "images/temp/" + blendImages(fileNames, path, userId);
    }

    public String getUrl(HttpServletRequest request) {
        return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/";
    }

    private String blendImages(List<String> fileNames, String path, Integer userId) {

        int chunkWidth, chunkHeight;
        int type;
        String newFileName = path + userId + "_final.jpg";

        //fetching image files  
        File[] imgFiles = new File[fileNames.size()];
        for (int i = 0; i < fileNames.size(); i++) {
            imgFiles[i] = new File(fileNames.get(i));
        }

        //creating a bufferd image array from image files  
        BufferedImage[] buffImages = new BufferedImage[fileNames.size()];
        for (int i = 0; i < fileNames.size(); i++) {
            try {
                buffImages[i] = ImageIO.read(imgFiles[i]);
            } catch (IOException ex) {
                Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        type = buffImages[0].getType();
        chunkWidth = buffImages[0].getWidth();
        chunkHeight = buffImages[0].getHeight();

        //Initializing the final image  
        BufferedImage finalImg = new BufferedImage(chunkWidth * 2, chunkHeight * 2, type);

        int num = 0;
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                finalImg.createGraphics().drawImage(buffImages[num], chunkWidth * j, chunkHeight * i, null);
                num++;
            }
        }

        System.out.println("Image concatenated.....");

        try {
            ImageIO.write(finalImg, "jpeg", new File(newFileName));
        } catch (IOException ex) {
            Logger.getLogger(Helper.class.getName()).log(Level.SEVERE, null, ex);
        }

        return userId.toString() + "_final.jpg";
    }
}