All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.ow2.util.geolocation.business.GeoLocatorBean Maven / Gradle / Ivy

/**
 * Copyright 2009-2012 Serli
 *
 * Licensed 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.ow2.util.geolocation.business;

import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.ow2.util.geolocation.business.entity.GeolocalisedProduct;
import org.ow2.util.geolocation.business.entity.ProductName;
import org.ow2.util.geolocation.business.entity.ProductVersion;
import com.maxmind.geoip.Location;
import com.maxmind.geoip.LookupService;
import com.maxmind.geoip.regionName;
import com.maxmind.geoip.timeZone;
import java.util.ArrayList;
import javax.ejb.Local;
import org.ow2.util.geolocation.business.entity.ManagedProduct;
import org.ow2.util.geolocation.business.entity.TechnicalAttributes;

/**
 * The geolocalization EJB.
 * 
 * @author mancelin
 */
@Stateless
@Local(GeoLocatorInterface.class)
public class GeoLocatorBean implements GeoLocatorInterface {
    /**
     * The logger.
     */
    private static Logger logger = Logger.getLogger(GeoLocatorBean.class.getName());
    /**
     * A null String.
     */
    private static final String NULL = "";
    /**
     * The persistance manager of the app.
     */
    @PersistenceContext(name = "entity")
    private EntityManager entityManager;
    /**
     * List of managed objects.
     */
    private List managedProducts = new ArrayList();
    /**
     * The path of the geolocalization database.
     */
    private static String geodbpath = NULL;
    /**
     * The path of the properties file.
     */
    private static final String PROP_FILE = "META-INF/" + GeoLocatorBean.class.getSimpleName().toLowerCase() + ".properties";

    static {
        try {
            Properties props = new Properties();
            props.load(GeoLocatorBean.class.getClassLoader().getResourceAsStream(PROP_FILE));
            geodbpath = props.getProperty("geodbpath");
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Add a new record in the app.
     * @param ipAddress the address of the user.
     * @param productName the product name.
     * @param productVersion the version name.
     * @param email the email address of the user.
     * @param jreVendor the jre vendor.
     * @param jreVersion the jre version.
     * @param jvmName the jvm name.
     * @param jvmVendor the jvm vendor.
     * @param jvmVersion the jvm version.
     * @param osName the os.
     * @param osArch os architecture.
     * @param osVersion os version.
     * @param numProc the number of processors.
     * @return succeed
     */
    public boolean addNewRecord(
            final String ipAddress,
            final String productName,
            final String productVersion,
            final String email,
            final String numProc,
            final String jreVersion,
            final String jreVendor,
            final String jvmVersion,
            final String jvmVendor,
            final String jvmName,
            final String osName,
            final String osArch,
            final String osVersion) {
        /** test if the added product is a managed one **/
        if (findManagedProductsWithNameAndVersion(productName, productVersion).size() > 0) {
            /** test if there is no equal record already added **/
            if (findWithIPAndNameAndVersion(ipAddress, productName, productVersion, email).size() <= 0) {
                try {
                    Location tmpLocation = geolocaliseIPAddress(ipAddress);
                    GeolocalisedProduct tmpProduct = new GeolocalisedProduct();
                    tmpProduct.setIpAddress(ipAddress);
                    tmpProduct.setEmail(email);
                    ProductName name = getProductNameFromPool(productName);
                    ProductVersion version = getProductVersionFromPool(productVersion);
                    TechnicalAttributes att = new TechnicalAttributes();
                    att.setJreVendor(jreVendor);
                    att.setJreVersion(jreVersion);
                    att.setJvmName(jvmName);
                    att.setJvmVendor(jvmVendor);
                    att.setJvmVersion(jvmVersion);
                    att.setNumProc(numProc);
                    att.setOsArch(osArch);
                    att.setOsName(osName);
                    att.setOsVersion(osVersion);
                    tmpProduct.setAttributes(att);
                    tmpProduct.setProductName(name);
                    tmpProduct.setProductVersion(version);
                    tmpProduct.setAreaCode(tmpLocation.area_code);
                    tmpProduct.setCity(tmpLocation.city);
                    tmpProduct.setCountryCode(tmpLocation.countryCode);
                    tmpProduct.setCountryName(tmpLocation.countryName);
                    tmpProduct.setDmaCode(tmpLocation.dma_code);
                    tmpProduct.setLatitude(tmpLocation.latitude);
                    tmpProduct.setLongitude(tmpLocation.longitude);
                    tmpProduct.setMetroCode(tmpLocation.metro_code);
                    tmpProduct.setPostalCode(tmpLocation.postalCode);
                    tmpProduct.setRegion(tmpLocation.region);
                    tmpProduct.setRegionName(regionName.regionNameByCode(tmpLocation.countryCode, tmpLocation.region));
                    tmpProduct.setTimezone(timeZone.timeZoneByCountryAndRegion(tmpLocation.countryCode, tmpLocation.region));
                    entityManager.persist(att);
                    entityManager.persist(tmpProduct);
                    entityManager.flush();
                    return true;
                } catch (Exception e) {
                    logger.log(Level.SEVERE, "User can't be geolocalised : "
                            + " " + ipAddress
                            + " " + email
                            + " " + productName
                            + " " + productVersion
                            + " - " +  e);
                }
            } else {
                logger.log(Level.SEVERE, "The product is already registered for this IP Address "
                    + productName + " " + productVersion + " @ " + ipAddress);
            }
        } else {
            logger.log(Level.SEVERE, "The product isn't managed : "
                        + productName + " " + productVersion);
        }
        return false;
    }
    
    /**
     * Return a new ProductName or existing one.
     * @param name the name of the product.
     * @return a productName object
     */
    private ProductName getProductNameFromPool(final String name) {
        ProductName tmpName = findAProductName(name);
        if (tmpName != null) {
            return tmpName;
        } else {
            tmpName = new ProductName();
            tmpName.setName(name);
            entityManager.persist(tmpName);
            entityManager.flush();
            return tmpName;
        }
    }

    /**
     * Return a new ProductVersion or existing one.
     * @param version the version of the product.
     * @return a ProductVersion object
     */
    private ProductVersion getProductVersionFromPool(final String version) {
        ProductVersion tmpVersion = findAProductVersion(version);
        if (tmpVersion != null) {
            return tmpVersion;
        } else {
            tmpVersion = new ProductVersion();
            tmpVersion.setVersion(version);
            entityManager.persist(tmpVersion);
            entityManager.flush();
            return tmpVersion;
        }
    }

    /**
     * Return the managed products.
     * @param productName the name of the product.
     * @param productVersion the version of the product.
     * @return the products managed by the application.
     */
    public List getLocalisedProducts(
            final String productName,
            final String productVersion) {
        List productsList = null;
        if (productName.equals(NULL) && productVersion.equals(NULL)) {
            productsList = findAll();
        } else if (productName.equals(NULL) && !productVersion.equals(NULL)) {
            productsList = findWithVersion(productVersion);
        } else if (!productName.equals(NULL) && productVersion.equals(NULL)) {
            productsList = findWithName(productName);
        } else {
            productsList = findWithNameAndVersion(productName, productVersion);
        }
        return productsList;
    }

    /**
     * Remove a product.
     * @param id the id of the product.
     */
    public void removeProduct(final Long id) {
        try {
            entityManager.remove(entityManager.find(GeolocalisedProduct.class, id));
            entityManager.flush();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Can't remove product " + e);
        }
    }
    
    /**
     * Add a managed product in the managed products list.
     * @param name name of the product.
     * @param version version of the product.
     * @return succeed
     */
    public boolean addManagedProduct(final String name, final String version) {
        try {
            if (!name.equals("") && !version.equals("")) {
                if (findManagedProductsWithNameAndVersion(name, version).size() <= 0) {
                    ManagedProduct prod = new ManagedProduct();
                    prod.setName(name);
                    prod.setVersion(version);
                    entityManager.persist(prod);
                    entityManager.flush();
                    return true;
                }
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Can't add managed product " + e);
        }
        return false;
    }

    /**
     * Remove a managed product.
     * @param id the id of the managed product.
     */
    public void removeManagedProduct(final Long id) {
        try {
            entityManager.remove(entityManager.find(ManagedProduct.class, id));
            entityManager.flush();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Can't remove managed product " + e);
        }
    }

    /**
     * Get the geolocation of an ip address.
     * @param ipAddress the ip address to locate.
     * @return the location.
     */
    private Location geolocaliseIPAddress(final String ipAddress) {
        LookupService cl = null;
        try {
            cl = new LookupService(geodbpath,
                    LookupService.GEOIP_MEMORY_CACHE);
            Location l2 = cl.getLocation(ipAddress);
            cl.close();
            return l2;
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Error for GEO service : " + e);
        }
        return null;
    }

    /**
     * @param name the name of the product.
     * @return wanted productName.
     */
    private ProductName findAProductName(final String name) {
        List tmpList = entityManager.createQuery(
                "SELECT p FROM ProductName AS p WHERE p.name "
                + "LIKE :custName")
                .setParameter("custName", name)
                .getResultList();
        if (tmpList.size() > 0) {
            return (ProductName) tmpList.get(0);
        } else {
            return null;
        }
    }

    /**
     * @param version the version of the product.
     * @return wanted productVersion.
     */
    private ProductVersion findAProductVersion(final String version) {
        List tmpList = entityManager.createQuery(
                "SELECT p FROM ProductVersion AS p WHERE p.version "
                + "LIKE :custVersion")
                .setParameter("custVersion", version)
                .getResultList();
        if (tmpList.size() > 0) {
            return (ProductVersion) tmpList.get(0);
        } else {
            return null;
        }
    }

    /**
     * @return all persited products.
     */
    private List findAll() {
        return entityManager.createQuery(
                "SELECT p FROM GeolocalisedProduct AS p")
                .getResultList();
    }

    /**
     * @param id id of the product.
     * @return a specific product.
     */
    public GeolocalisedProduct findAProduct(final String id) {
        List tmpList = entityManager.createQuery(
                "SELECT p FROM GeolocalisedProduct AS p WHERE p.id "
                + "LIKE :custId")
                .setParameter("custId", Long.valueOf(id))
                .getResultList();
        if (tmpList.size() > 0) {
            return (GeolocalisedProduct) tmpList.get(0);
        } else {
            return null;
        }
    }

    /**
     * @return all persited product names.
     */
    public List findAllProductsName() {
        return entityManager.createQuery(
                "SELECT DISTINCT p.productName.name FROM GeolocalisedProduct AS p")
                .getResultList();
    }

    /**
     * @return all persited product versions.
     */
    public List findAllProductsVersions() {
        return entityManager.createQuery(
                "SELECT DISTINCT p.productVersion.version FROM GeolocalisedProduct AS p")
                .getResultList();
    }

    /**
     * @param productName the filter name.
     * @return all persited products with the right name.
     */
    private List findWithName(final String productName) {
        return entityManager.createQuery(
                "SELECT p FROM GeolocalisedProduct AS p WHERE p.productName.name "
                + "LIKE :custName")
                .setParameter("custName", productName)
                .getResultList();
    }

    /**
     *
     * @param productVersion the filter version.
     * @return all persited products with the right version.
     */
    private List findWithVersion(final String productVersion) {
        return entityManager.createQuery(
                "SELECT p FROM GeolocalisedProduct AS p "
                + "WHERE p.productVersion.version LIKE :custVersion")
                .setParameter("custVersion", productVersion)
                .getResultList();
    }

    /**
     * 
     * @param productName the filter name.
     * @param productVersion the filter version.
     * @return all persited products with the right name and right version.
     */
    private List findWithNameAndVersion(final String productName, final String productVersion) {
        return entityManager.createQuery(
                "SELECT p FROM GeolocalisedProduct AS p "
                + "WHERE p.productName.name LIKE :custName "
                + "AND p.productVersion.version LIKE :custVersion")
                .setParameter("custName", productName)
                .setParameter("custVersion", productVersion)
                .getResultList();
    }

    /**
     * TODO : add email verification.
     * @param ip the ip address.
     * @param productName the filter name.
     * @param productVersion the filter version.
     * @param userEmail the email address of the user.
     * @return all persited products with the right name and right version.
     */
    private List findWithIPAndNameAndVersion(final String ip,
            final String productName,
            final String productVersion,
            final String userEmail) {
        return entityManager.createQuery(
                "SELECT p FROM GeolocalisedProduct AS p "
                + "WHERE p.productName.name LIKE :custName "
                + "AND p.productVersion.version LIKE :custVersion "
                + "AND p.ipAddress LIKE :custIP "
                + "AND p.email LIKE :custEmail")
                .setParameter("custName", productName)
                .setParameter("custVersion", productVersion)
                .setParameter("custIP", ip)
                .setParameter("custEmail", userEmail)
                .getResultList();
    }

    /**
     * @return all persited managed products.
     */
    public List findAllManagedProducts() {
        return entityManager.createQuery(
                "SELECT p FROM ManagedProduct AS p")
                .getResultList();
    }

    /**
     *
     * @param productName the filter name.
     * @param productVersion the filter version.
     * @return all persited products with the right name and right version.
     */
    public List findManagedProductsWithNameAndVersion(final String productName, final String productVersion) {
        return entityManager.createQuery(
                "SELECT p FROM ManagedProduct AS p "
                + "WHERE UPPER(p.name) LIKE UPPER(:custName) "
                + "AND p.version LIKE :custVersion")
                .setParameter("custName", productName)
                .setParameter("custVersion", productVersion)
                .getResultList();
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy