<commit_before>/*
    open source routing machine
    Copyright (C) <NAME>, others 2010

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.

This program 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 Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/licenses/agpl.txt.
 */

#ifndef VIAROUTEPLUGIN_H_
#define VIAROUTEPLUGIN_H_

#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

#include "ObjectForPluginStruct.h"

#include "BaseDescriptor.h"
#include "BasePlugin.h"
#include "RouteParameters.h"
#include "GPXDescriptor.h"
#include "JSONDescriptor.h"

#include "../DataStructures/HashTable.h"
#include "../DataStructures/StaticGraph.h"
#include "../DataStructures/SearchEngine.h"

#include "../Util/StringUtil.h"

class ViaRoutePlugin : public BasePlugin {
private:
    NodeInformationHelpDesk * nodeHelpDesk;
    std::vector<std::string> * names;
    StaticGraph<EdgeData> * graph;
    HashTable<std::string, unsigned> descriptorTable;
    std::string pluginDescriptorString;

    SearchEngine<EdgeData, StaticGraph<EdgeData> > * searchEngine;
public:

    ViaRoutePlugin(ObjectsForQueryStruct * objects, std::string psd = "viaroute") : pluginDescriptorString(psd) {
        nodeHelpDesk = objects->nodeHelpDesk;
        graph = objects->graph;
        names = objects->names;

        searchEngine = new SearchEngine<EdgeData, StaticGraph<EdgeData> >(graph, nodeHelpDesk, names);

        descriptorTable.Set("", 0); //default descriptor
        descriptorTable.Set("kml", 0);
        descriptorTable.Set("json", 1);
        descriptorTable.Set("gpx", 2);
    }

    virtual ~ViaRoutePlugin() {
    	DELETE( searchEngine );
    }

    std::string GetDescriptor() { return pluginDescriptorString; }
    std::string GetVersionString() { return std::string("0.3 (DL)"); }
    void HandleRequest(RouteParameters routeParameters, http::Reply& reply) {
        //check number of parameters
        if(0 == routeParameters.options["start"].size() || 0 == routeParameters.options["dest"].size() ) {
            reply = http::Reply::stockReply(http::Reply::badRequest);
            return;
        }

        //Get start and end Coordinate
        std::string start = routeParameters.options["start"];
        std::string dest = routeParameters.options["dest"];

        std::vector<std::string> textCoord = split (start, ',');

        int lat1 = static_cast<int>(100000.*atof(textCoord[0].c_str()));
        int lon1 = static_cast<int>(100000.*atof(textCoord[1].c_str()));

        textCoord = split (dest, ',');

        int lat2 = static_cast<int>(100000.*atof(textCoord[0].c_str()));
        int lon2 = static_cast<int>(100000.*atof(textCoord[1].c_str()));

        _Coordinate startCoord(lat1, lon1);
        _Coordinate targetCoord(lat2, lon2);
        RawRouteData rawRoute;

        if(false == checkCoord(startCoord) || false == checkCoord(targetCoord)) {
            reply = http::Reply::stockReply(http::Reply::badRequest);
            return;
        }
        rawRoute.rawViaNodeCoordinates.push_back(startCoord);

        INFO("[debug] number of vianodes: " << routeParameters.viaPoints.size());
        for(unsigned i = 0; i < routeParameters.viaPoints.size(); i++) {
            textCoord = split (routeParameters.viaPoints[i], ',');
            if(textCoord.size() != 2) {
                reply = http::Reply::stockReply(http::Reply::badRequest);
                return;
            }
            int vialat = static_cast<int>(100000.*atof(textCoord[0].c_str()));
            int vialon = static_cast<int>(100000.*atof(textCoord[1].c_str()));
            INFO("[debug] via" << i << ": " << vialat << "," << vialon);
            _Coordinate viaCoord(vialat, vialon);
            if(false == checkCoord(viaCoord)) {
                reply = http::Reply::stockReply(http::Reply::badRequest);
                return;
            }
            rawRoute.rawViaNodeCoordinates.push_back(viaCoord);
        }
        rawRoute.rawViaNodeCoordinates.push_back(targetCoord);
        vector<PhantomNode> phantomNodeVector(rawRoute.rawViaNodeCoordinates.size());
        bool errorOccurredFlag = false;

        for(unsigned i = 0; i < rawRoute.rawViaNodeCoordinates.size(); i++) {
        	searchEngine->FindPhantomNodeForCoordinate( rawRoute.rawViaNodeCoordinates[i], phantomNodeVector[i]);
            if(!rawRoute.rawViaNodeCoordinates[i].isSet()) {
                errorOccurredFlag = true;
            }
        }

        rawRoute.Resize();
        unsigned distance = 0;

        for(unsigned i = 0; i < phantomNodeVector.size()-1 && !errorOccurredFlag; i++) {
            PhantomNodes segmentPhantomNodes;
            segmentPhantomNodes.startPhantom = phantomNodeVector[i];
            segmentPhantomNodes.targetPhantom = phantomNodeVector[i+1];
            INFO(segmentPhantomNodes);
            std::vector< _PathData > path;
            unsigned distanceOfSegment = searchEngine->ComputeRoute(segmentPhantomNodes, path);

            if(UINT_MAX == distanceOfSegment ) {
                errorOccurredFlag = true;
                INFO( "Error occurred, path not found" );
                distance = UINT_MAX;
                break;
            } else {
                distance += distanceOfSegment;
            }

            //put segments at correct position of routes raw data
            rawRoute.segmentEndCoordinates[i] = (segmentPhantomNodes);
            rawRoute.routeSegments[i] = path;
        }

        INFO("Found path of length: " << distance);

        reply.status = http::Reply::ok;

        BaseDescriptor<SearchEngine<EdgeData, StaticGraph<EdgeData> > > * desc;
        std::string JSONParameter = routeParameters.options.Find("jsonp");
        if("" != JSONParameter) {
            reply.content += JSONParameter;
            reply.content += "(\n";
        }

        _DescriptorConfig descriptorConfig;
        unsigned descriptorType = descriptorTable[routeParameters.options.Find("output")];
        unsigned short zoom = 18;
        if(routeParameters.options.Find("z") != ""){
            zoom = atoi(routeParameters.options.Find("z").c_str());
            if(18 < zoom)
                zoom = 18;
        }
        descriptorConfig.z = zoom;
        if(routeParameters.options.Find("instructions") == "false") {
            descriptorConfig.instructions = false;
        }
        if(routeParameters.options.Find("geometry") == "false" ) {
            descriptorConfig.geometry = false;
        }
        if("cmp" == routeParameters.options.Find("geomformat") || "cmp6" == routeParameters.options.Find("geomformat")  ) {
            descriptorConfig.encodeGeometry = true;
        }

        switch(descriptorType){
        case 0:
            desc = new JSONDescriptor<SearchEngine<EdgeData, StaticGraph<EdgeData> > >();
<commit_msg>Removing KML descriptor from list of supported formats<commit_after>/*
    open source routing machine
    Copyright (C) <NAME>, others 2010

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU AFFERO General Public License as published by
the Free Software Foundation; either version 3 of the License, or
any later version.

This program 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 Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
or see http://www.gnu.org/licenses/agpl.txt.
 */

#ifndef VIAROUTEPLUGIN_H_
#define VIAROUTEPLUGIN_H_

#include <cstdlib>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

#include "ObjectForPluginStruct.h"

#include "BaseDescriptor.h"
#include "BasePlugin.h"
#include "RouteParameters.h"
#include "GPXDescriptor.h"
#include "JSONDescriptor.h"

#include "../DataStructures/HashTable.h"
#include "../DataStructures/StaticGraph.h"
#include "../DataStructures/SearchEngine.h"

#include "../Util/StringUtil.h"

class ViaRoutePlugin : public BasePlugin {
private:
    NodeInformationHelpDesk * nodeHelpDesk;
    std::vector<std::string> * names;
    StaticGraph<EdgeData> * graph;
    HashTable<std::string, unsigned> descriptorTable;
    std::string pluginDescriptorString;

    SearchEngine<EdgeData, StaticGraph<EdgeData> > * searchEngine;
public:

    ViaRoutePlugin(ObjectsForQueryStruct * objects, std::string psd = "viaroute") : pluginDescriptorString(psd) {
        nodeHelpDesk = objects->nodeHelpDesk;
        graph = objects->graph;
        names = objects->names;

        searchEngine = new SearchEngine<EdgeData, StaticGraph<EdgeData> >(graph, nodeHelpDesk, names);

        descriptorTable.Set("", 0); //default descriptor
        descriptorTable.Set("json", 0);
        descriptorTable.Set("gpx", 1);
    }

    virtual ~ViaRoutePlugin() {
    	DELETE( searchEngine );
    }

    std::string GetDescriptor() { return pluginDescriptorString; }
    std::string GetVersionString() { return std::string("0.3 (DL)"); }
    void HandleRequest(RouteParameters routeParameters, http::Reply& reply) {
        //check number of parameters
        if(0 == routeParameters.options["start"].size() || 0 == routeParameters.options["dest"].size() ) {
            reply = http::Reply::stockReply(http::Reply::badRequest);
            return;
        }

        //Get start and end Coordinate
        std::string start = routeParameters.options["start"];
        std::string dest = routeParameters.options["dest"];

        std::vector<std::string> textCoord = split (start, ',');

        int lat1 = static_cast<int>(100000.*atof(textCoord[0].c_str()));
        int lon1 = static_cast<int>(100000.*atof(textCoord[1].c_str()));

        textCoord = split (dest, ',');

        int lat2 = static_cast<int>(100000.*atof(textCoord[0].c_str()));
        int lon2 = static_cast<int>(100000.*atof(textCoord[1].c_str()));

        _Coordinate startCoord(lat1, lon1);
        _Coordinate targetCoord(lat2, lon2);
        RawRouteData rawRoute;

        if(false == checkCoord(startCoord) || false == checkCoord(targetCoord)) {
            reply = http::Reply::stockReply(http::Reply::badRequest);
            return;
        }
        rawRoute.rawViaNodeCoordinates.push_back(startCoord);

        INFO("[debug] number of vianodes: " << routeParameters.viaPoints.size());
        for(unsigned i = 0; i < routeParameters.viaPoints.size(); i++) {
            textCoord = split (routeParameters.viaPoints[i], ',');
            if(textCoord.size() != 2) {
                reply = http::Reply::stockReply(http::Reply::badRequest);
                return;
            }
            int vialat = static_cast<int>(100000.*atof(textCoord[0].c_str()));
            int vialon = static_cast<int>(100000.*atof(textCoord[1].c_str()));
            INFO("[debug] via" << i << ": " << vialat << "," << vialon);
            _Coordinate viaCoord(vialat, vialon);
            if(false == checkCoord(viaCoord)) {
                reply = http::Reply::stockReply(http::Reply::badRequest);
                return;
            }
            rawRoute.rawViaNodeCoordinates.push_back(viaCoord);
        }
        rawRoute.rawViaNodeCoordinates.push_back(targetCoord);
        vector<PhantomNode> phantomNodeVector(rawRoute.rawViaNodeCoordinates.size());
        bool errorOccurredFlag = false;

        for(unsigned i = 0; i < rawRoute.rawViaNodeCoordinates.size(); i++) {
        	searchEngine->FindPhantomNodeForCoordinate( rawRoute.rawViaNodeCoordinates[i], phantomNodeVector[i]);
            if(!rawRoute.rawViaNodeCoordinates[i].isSet()) {
                errorOccurredFlag = true;
            }
        }

        rawRoute.Resize();
        unsigned distance = 0;

        for(unsigned i = 0; i < phantomNodeVector.size()-1 && !errorOccurredFlag; i++) {
            PhantomNodes segmentPhantomNodes;
            segmentPhantomNodes.startPhantom = phantomNodeVector[i];
            segmentPhantomNodes.targetPhantom = phantomNodeVector[i+1];
            INFO(segmentPhantomNodes);
            std::vector< _PathData > path;
            unsigned distanceOfSegment = searchEngine->ComputeRoute(segmentPhantomNodes, path);

            if(UINT_MAX == distanceOfSegment ) {
                errorOccurredFlag = true;
                INFO( "Error occurred, path not found" );
                distance = UINT_MAX;
                break;
            } else {
                distance += distanceOfSegment;
            }

            //put segments at correct position of routes raw data
            rawRoute.segmentEndCoordinates[i] = (segmentPhantomNodes);
            rawRoute.routeSegments[i] = path;
        }

        INFO("Found path of length: " << distance);

        reply.status = http::Reply::ok;

        BaseDescriptor<SearchEngine<EdgeData, StaticGraph<EdgeData> > > * desc;
        std::string JSONParameter = routeParameters.options.Find("jsonp");
        if("" != JSONParameter) {
            reply.content += JSONParameter;
            reply.content += "(\n";
        }

        _DescriptorConfig descriptorConfig;
        unsigned descriptorType = descriptorTable[routeParameters.options.Find("output")];
        unsigned short zoom = 18;
        if(routeParameters.options.Find("z") != ""){
            zoom = atoi(routeParameters.options.Find("z").c_str());
            if(18 < zoom)
                zoom = 18;
        }
        descriptorConfig.z = zoom;
        if(routeParameters.options.Find("instructions") == "false") {
            descriptorConfig.instructions = false;
        }
        if(routeParameters.options.Find("geometry") == "false" ) {
            descriptorConfig.geometry = false;
        }
        if("cmp" == routeParameters.options.Find("geomformat") || "cmp6" == routeParameters.options.Find("geomformat")  ) {
            descriptorConfig.encodeGeometry = true;
        }
        switch(descriptorType){
        case 0:
            desc = new JSONDescriptor<SearchEngine<EdgeData, StaticGraph<EdgeData> > >();

{'fraction_non_alphanumeric': 0.12179530771846311, 'fraction_numerical': 0.012444746684801089, 'mean_word_length': 2.8537735849056602, 'pattern_counts': {'":': 2, '<': 95, '<?xml version=': 0, '>': 69, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '480699', 'n_tokens_mistral': 4270, 'n_tokens_neox': 4025, 'n_words': 909}