org.gofleet.openLS.ddbb.dao.RoutingDAO.java Source code

Java tutorial

Introduction

Here is the source code for org.gofleet.openLS.ddbb.dao.RoutingDAO.java

Source

/*
 * Copyright (C) 2011, Emergya (http://www.emergya.es)
 *
 * @author <a href="mailto:marias@emergya.com">Mara Arias</a>
 *
 * This file is part of GoFleet
 *
 * This software is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * As a special exception, if you link this library with other files to
 * produce an executable, this library does not by itself cause the
 * resulting executable to be covered by the GNU General Public License.
 * This exception does not however invalidate any other reasons why the
 * executable file might be covered by the GNU General Public License.
 */
package org.gofleet.openLS.ddbb.dao;

import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.annotation.Resource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import net.opengis.gml.v_3_1_1.LineStringType;
import net.opengis.xls.v_1_2_0.DetermineRouteRequestType;
import net.opengis.xls.v_1_2_0.DetermineRouteResponseType;
import net.opengis.xls.v_1_2_0.DistanceType;
import net.opengis.xls.v_1_2_0.RouteGeometryType;
import net.opengis.xls.v_1_2_0.RouteHandleType;
import net.opengis.xls.v_1_2_0.RouteInstructionsListType;
import net.opengis.xls.v_1_2_0.RouteMapType;
import net.opengis.xls.v_1_2_0.RouteSummaryType;
import net.opengis.xls.v_1_2_0.WayPointListType;
import net.opengis.xls.v_1_2_0.WayPointType;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.gofleet.configuration.Configuration;
import org.gofleet.openLS.ddbb.GeoCoding;
import org.gofleet.openLS.ddbb.bean.HBA;
import org.gofleet.openLS.util.GeoUtil;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernatespatial.GeometryUserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.CoordinateSequence;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import com.vividsolutions.jts.geom.impl.CoordinateArraySequence;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

@Repository
public class RoutingDAO {
    private static final String GID_ROUTING = Configuration.get("ROUTING_ID", "gid");
    private static final String TABLE_ROUTING = Configuration.get("ROUTING_TABLE", "routing");

    private static final String EPSG_4326 = Configuration.get("ROUTING_EPSG", "EPSG:4326");

    private GeometryFactory gf = new GeometryFactory();

    private HibernateTemplate hibernateTemplate;

    private static Log LOG = LogFactory.getLog(RoutingDAO.class);

    @SuppressWarnings("unused")
    @Resource
    private GeoCoding geocoding;
    private Unmarshaller unmarshaller;
    private JAXBContext context;
    private Marshaller marshaller;

    /**
     * 
     */
    public RoutingDAO() {
        try {
            unmarshaller = JAXBContext.newInstance(LineStringType.class).createUnmarshaller();
            context = JAXBContext.newInstance("org.jvnet.ogc.gml.v_3_1_1.jts");
            marshaller = context.createMarshaller();
        } catch (JAXBException e) {
            LOG.error(e, e);
        }
    }

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    @Transactional(readOnly = true)
    public DetermineRouteResponseType routePlan(final DetermineRouteRequestType param) {

        HibernateCallback<DetermineRouteResponseType> action = new HibernateCallback<DetermineRouteResponseType>() {

            @SuppressWarnings("unchecked")
            public DetermineRouteResponseType doInHibernate(Session session)
                    throws HibernateException, SQLException {
                Query consulta = session.getNamedQuery("tsp");

                WayPointListType wayPointList = param.getRoutePlan().getWayPointList();

                List<Geometry> stops = new LinkedList<Geometry>();
                for (WayPointType wayPoint : wayPointList.getViaPoint()) {
                    stops.add(GeoUtil.getPoint(wayPoint));
                }
                stops.add(GeoUtil.getPoint(wayPointList.getEndPoint()));

                consulta.setString("tablename", TABLE_ROUTING);
                consulta.setParameterList("stoptable", stops, GeometryUserType.TYPE);
                consulta.setString("gid", GID_ROUTING);
                consulta.setParameter("start", GeoUtil.getPoint(wayPointList.getStartPoint()),
                        GeometryUserType.TYPE);

                consulta.setReadOnly(true);
                LOG.debug(consulta);

                return getRouteResponse(consulta.list());

            }

        };
        return hibernateTemplate.executeWithNativeSession(action);
    }

    private RouteGeometryType getRouteGeometry(com.vividsolutions.jts.geom.LineString geometry)
            throws JAXBException, ParseException {

        LineString line = (LineString) (new WKTReader()).read(geometry.toString()).getGeometryN(0);

        if (LOG.isTraceEnabled())
            marshaller.marshal(line, System.out);

        StringWriter writer = new StringWriter();
        marshaller.marshal(line, writer);
        StringReader reader = new StringReader(writer.toString());

        LineStringType lineString = ((JAXBElement<LineStringType>) unmarshaller.unmarshal(reader)).getValue();

        RouteGeometryType routeGeometry = new RouteGeometryType();
        routeGeometry.setLineString(lineString);
        return routeGeometry;
    }

    private RouteSummaryType getRouteSummary(Double cost) {
        RouteSummaryType res = new RouteSummaryType();
        DistanceType coste = new DistanceType();
        if (cost.isInfinite() || cost.isNaN())
            coste.setValue(BigDecimal.valueOf(0d));
        else
            coste.setValue(BigDecimal.valueOf(cost));
        res.setTotalDistance(coste);
        return res;
    }

    private List<RouteMapType> getRouteMap(List<Coordinate> lineStrings) {
        List<RouteMapType> res = new ArrayList<RouteMapType>(0);
        return res;
    }

    private RouteInstructionsListType getInstructionsList(List<Coordinate> lineStrings) {
        RouteInstructionsListType res = new RouteInstructionsListType();
        return res;
    }

    private RouteHandleType getRouteHandle(List<Coordinate> lineStrings) {
        RouteHandleType handleType = new RouteHandleType();
        handleType.setRouteID("-1");
        handleType.setServiceID("-1");
        return handleType;
    }

    private DetermineRouteResponseType getRouteResponse(List<HBA> resultado) throws SQLException {

        DetermineRouteResponseType res = new DetermineRouteResponseType();
        Long last = -1l;
        List<Coordinate> coords = new LinkedList<Coordinate>();
        double cost = 0;
        for (HBA step : resultado) {
            try {
                Long current = step.getId();
                if (!current.equals(last)) {
                    coords.addAll(Arrays.asList(step.getGeometria().getCoordinates()));
                    cost += step.getCost();
                } else
                    LOG.trace("Repeating step " + current);
                last = current;
            } catch (Exception e) {
                LOG.error("Unknown Step", e);
            }
        }

        RouteGeometryType routeGeometry;
        try {
            CoordinateSequence cs = new CoordinateArraySequence(coords.toArray(new Coordinate[] {}));
            LineString line = new LineString(cs, gf);
            routeGeometry = getRouteGeometry(line);
            res.setRouteGeometry(routeGeometry);
        } catch (JAXBException e) {
            LOG.error(e, e);
        } catch (ParseException e) {
            LOG.error(e, e);
        }

        res.setRouteHandle(getRouteHandle(coords));
        res.setRouteInstructionsList(getInstructionsList(coords));
        res.setRouteMap(getRouteMap(coords));
        res.setRouteSummary(getRouteSummary(cost));
        return res;
    }
}