1   package examples.bookTrading;
2   
3   import java.sql.Connection;
4   import java.sql.PreparedStatement;
5   import java.sql.ResultSet;
6   import java.sql.SQLException;
7   import java.sql.Timestamp;
8   import java.text.ParseException;
9   import java.text.SimpleDateFormat;
10  import java.util.ArrayList;
11  import java.util.Collections;
12  import java.util.Comparator;
13  import java.util.HashMap;
14  import java.util.Iterator;
15  import java.util.LinkedHashMap;
16  import java.util.LinkedList;
17  import java.util.List;
18  import java.util.Map;
19  import java.util.Map.Entry;
20  import java.util.Random;
21  import java.util.Set;
22  import java.util.StringTokenizer;
23  import java.util.TreeMap;
24  import java.util.concurrent.ConcurrentHashMap;
25  
26  import de.uni_stuttgart.informatik.canu.mobisim.core.Position3D;
27  
28  /**
29   * This user-defined Java class is used as an interface with the database
30   * for retrieving road network and agent preferences.
31   * @author prajakta
32   *
33   */
34  public class DataAccess {
35  
36  
37      static HashMap<String,Double> weightMap = new HashMap<String,Double>();
38      static ValueComparator bvc =  new ValueComparator(weightMap);
39      static TreeMap<String,Double> sortedWeightMap = new TreeMap(bvc);
40  
41      static HashMap<String,Double> RIQMap = new HashMap<String,Double>();
42      static ValueComparator bvcRIQ =  new ValueComparator(RIQMap);
43      static TreeMap<String,Double> sortedWeightMapRIQ = new TreeMap(bvcRIQ);
44  
45  
46      static HashMap<String,String> sortedNPrefMap = new HashMap();
47  
48      static ConcurrentHashMap<String,Double> pathLengthMap = new ConcurrentHashMap<String,Double>();
49  
50      static Connection c = null;
51      static double travelTime = 0.0;
52  
53      static ConcurrentHashMap<String,Double> bandClassifiedVehicleMap = new ConcurrentHashMap<String,Double>();
54      static ConcurrentHashMap routeRankMap = new ConcurrentHashMap();
55  
56  
57  
58      static ConcurrentHashMap<String, PreferenceUtilityIndex> registeredVehicleInfo = new ConcurrentHashMap();
59      static ConcurrentHashMap pathIDTopath = new ConcurrentHashMap();
60      static ConcurrentHashMap routeParamMapTD = new ConcurrentHashMap();
61  
62  
63      //mega map
64      static ConcurrentHashMap<String,TreeMap> masterMap = new ConcurrentHashMap<String,TreeMap>();
65      static ConcurrentHashMap<String,TreeMap> masterMapCpy = new ConcurrentHashMap<String,TreeMap>();
66  
67  
68    //  static ValueComparator bvcRouteRank =  new ValueComparator(routeRankMap);
69    //  static TreeMap<String,Double> sortedRouteRankMap = new TreeMap(bvcRouteRank);
70  
71      static ConcurrentHashMap pUtilityMap = new ConcurrentHashMap();
72      static ValueComparator bvcPUtility =  new ValueComparator(pUtilityMap);
73      static TreeMap<String,Double> sortedPUtilityMap = new TreeMap(bvcPUtility);
74      private static String tempSegmentList;
75  
76  
77      ConcurrentHashMap utilityIDMap = new ConcurrentHashMap();
78      ValueComparator bvcutilityID =  new ValueComparator(utilityIDMap);
79      TreeMap sortedUtilityIDMap = new TreeMap(bvcutilityID);
80      double storedUtilityIndex = 0.0;
81      static ConcurrentHashMap agentCountMap = new ConcurrentHashMap();
82      
83      /**
84       * This method checks if the congested path is on the vehicle route
85       * @param vehicleID ID of the vehicle for which path is to be checked
86       * @param xCoord x-ccordinate of the segment
87       * @return notification pattern information of the vehicles
88       */
89      
90      public static synchronized NotificationPattern checkPathForRIQ(String vehicleID,double xCoord)
91      {
92          String path = null;
93          path = getVehiclePath(vehicleID);
94          String pathRIQ = null;
95          NotificationPattern notifPattern = new NotificationPattern();
96  
97          String sqlSelectRIQ = null;
98          if(xCoord!=0.0){
99              sqlSelectRIQ = "select segmentID,reasonforcongestion from NotificationPattern where vehicleID='" +vehicleID+ "' AND junctionID in (select junctionID from junctions where jnxcoord >="+xCoord+") order by jnorder";
100         }else{
101             sqlSelectRIQ = "select segmentID,reasonforcongestion from NotificationPattern where vehicleID='" +vehicleID+ "'";
102         }
103         ResultSet rsSelectRIQ = null;
104         if(path!=null){
105 
106 
107         try {
108             PreparedStatement st = null;
109             st =  QueueManager.getConnection().prepareStatement(sqlSelectRIQ);
110             rsSelectRIQ = st.executeQuery();
111 
112             if(rsSelectRIQ!=null)
113             {
114                 while(rsSelectRIQ.next())
115                 {
116                     String segID = rsSelectRIQ.getString(1);
117                     int congCause = rsSelectRIQ.getInt(2);
118                     if(path.indexOf(segID)>-1)
119                     {
120                         pathRIQ = segID;
121                         notifPattern.setSegmentID(pathRIQ);
122                         notifPattern.setReasonForCongestion(congCause);
123                         notifPattern.setVehicleID(vehicleID);
124                         break;
125                     }
126                 }
127             }
128             st.close();
129         } catch (SQLException e) {
130             e.printStackTrace();
131         }
132         return notifPattern;
133         }else{
134             return null;
135         }
136     }
137     
138     
139     /**
140      * This method checks for segment count in vehicle list
141      * @param vehicleList list of vehicles
142      */
143     public static synchronized void addToAgentCntMap(String vehicleList){
144         Set entries = agentCountMap.entrySet();
145         int cnt = 0;
146 
147         if(entries!=null && !entries.isEmpty()){
148         for(Iterator it = entries.iterator(); it.hasNext();) {
149              Map.Entry entry = (Entry) it.next();
150              String vList =  (String) entry.getKey().toString();
151              cnt=  Integer.parseInt((entry.getValue().toString()));
152              if(vList!=null && vehicleList!=null){
153                  if(vehicleList.indexOf(vList)>-1){
154                      StringTokenizer st = new StringTokenizer(vehicleList,",");
155                      while(st!=null && st.hasMoreTokens()){
156                          String tk = st.nextToken();
157                         cnt++;
158                      }
159                  }
160              }
161         }
162         agentCountMap.put(vehicleList, cnt);
163         }
164 
165 
166     }
167     
168     /**
169      * This method retrieves the vehicle path for the given vehicle ID
170      * @param vehicleID ID of the vehicle
171      * @return vehicle path
172      */
173     public static synchronized String getVehiclePath(String vehicleID)
174     {
175         //String selectVehiclePath = "select JourneyID from VEHICLEAGENT where vehicleID= '"+vehicleID+"'";
176         String selectPath = "select path from Journey where STATUS=0 and journeyID in (select JourneyID from VEHICLEAGENT where vehicleID= '"+vehicleID+"')" ;
177         ResultSet rsSelectPath = null;
178         ResultSet rsSelectPathForJourney = null;
179         String jID = null;
180         String vPath = null;
181         try {
182         //  PreparedStatement st = null;
183         //    st =  getConnection().prepareStatement(selectVehiclePath);
184 
185         //    rsSelectPath = st.executeQuery();
186         //    while(rsSelectPath.next())
187         //    {
188         //      jID = rsSelectPath.getString(1);
189         //    }
190         //  st.close();
191           //  selectPath = "select path from Journey where journeyID= '"+jID+"' and STATUS=0";
192             PreparedStatement stForJourney = null;
193           //  if(jID!=null)
194         //  {
195                 stForJourney =  QueueManager.getConnection().prepareStatement(selectPath);
196             //  System.out.println("Jerk statement : "+selectPath);
197                 rsSelectPathForJourney = stForJourney.executeQuery();
198 
199             while(rsSelectPathForJourney!=null && rsSelectPathForJourney.next())
200             {
201                 vPath = rsSelectPathForJourney.getString(1);
202             }
203         //  }
204             stForJourney.close();
205         } catch (SQLException e) {
206         //  System.out.println("!!!!!!!!!!!!!!!!!!!!!!!For vehicle ID : "+vehicleID);
207             e.printStackTrace();
208         }
209         return vPath ;
210     }
211     
212     /**
213      * This method retrieves alternate routes from a junction
214      * @param junctionID ID of the junction
215      * @return list of routes
216      */
217     public static synchronized ArrayList<String> getAlternateRoutesFromJunction(String junctionID)
218     {
219         String pathRIQ = null;
220         String sqlSelectJunctionSeg = "select segmentID from JunctionSegment where JunctionID='"+junctionID+"'";
221         ResultSet rsSelectJunction = null;
222         ArrayList<String> segmentList = new ArrayList<String>();
223         String segID = null;
224         try {
225             PreparedStatement st = null;
226             st =  QueueManager.getConnection().prepareStatement(sqlSelectJunctionSeg);
227             rsSelectJunction = st.executeQuery();
228 
229             if(rsSelectJunction!=null)
230             {
231                 while(rsSelectJunction.next())
232                 {
233                     segID = rsSelectJunction.getString(1);
234                     segmentList.add(segID);
235                 }
236             }
237             st.close();
238         } catch (SQLException e) {
239             e.printStackTrace();
240         }
241         return segmentList;
242     }
243 
244 
245 
246     public static String[][] getJunctionCoordinates()
247     {
248         String[][] junctionCoord = new String[1][1];
249         return junctionCoord;
250     }
251 
252     public static void createCongNotifPatterns()
253     {
254         String sqlCongNotifPattern = "SELECT SEGMENTID, JUNCTIONID,REASONFORCONGESTION,COUNT(NOTIFICATIONID),AVG(CONGESTIONVAL) FROM NOTIFICATIONS WHERE TIMESTAMP BETWEEN '2011-08-07 20:08:08' AND '2011-08-13 16:08:08' GROUP BY REASONFORCONGESTION, SEGMENTID,JUNCTIONID";
255         ResultSet rsCreateNotif = null;
256         String segID = null,junctionID = null, reasonForCong = null;
257         int notifCnt;
258         float congVal;
259         String toDate,fromDate = null;
260         java.sql.Date sqlDate = null,toSqlDate = null;
261         String sqlInsertNotifPattern = "INSERT INTO NOTIFICATIONPATTERN(PATTERNID, SEGMENTID, TIMEOFDAYFROM, TIMEOFDAYTO, DAYOFWEEK, REASONFORCONGESTION, EXTRATIME, EXTRADIST, JUNCTIONID)"+
262                                         "VALUES (?,?,?,?,?,?,?,?,?)";
263         try {
264             PreparedStatement st = null;
265             st =  QueueManager.getConnection().prepareStatement(sqlCongNotifPattern);
266             rsCreateNotif = st.executeQuery();
267             try {
268                 SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
269                 fromDate = "2011-08-07 20:08:08";
270                 java.util.Date utilDate = formatter.parse(fromDate);
271                 sqlDate = new java.sql.Date(utilDate.getTime());
272                 System.out.println("date:" + fromDate);
273                 System.out.println("sqlDate:" + sqlDate);
274 
275                 toDate = "2011-08-13 16:08:08";
276                 java.util.Date toUtilDate = formatter.parse(toDate);
277                 toSqlDate = new java.sql.Date(toUtilDate.getTime());
278                 System.out.println("date:" + toDate);
279                 System.out.println("sqlDate:" + toSqlDate);
280               } catch (ParseException e) {
281                 System.out.println(e.toString());
282                 e.printStackTrace();
283               }
284 
285             if(rsCreateNotif!=null)
286             {
287                 segID = rsCreateNotif.getString(1);
288                 junctionID = rsCreateNotif.getString(2);
289                 reasonForCong = rsCreateNotif.getString(3);
290                 notifCnt = rsCreateNotif.getInt(4);
291                 congVal = rsCreateNotif.getInt(5);
292             }
293 
294             st.clearParameters();
295             st =  QueueManager.getConnection().prepareStatement(sqlInsertNotifPattern);
296             st.setString(1, "n2");
297             st.setString(2, segID);
298             st.setString(3,reasonForCong);
299             st.setTimestamp(4,new Timestamp(sqlDate.getTime()));
300             st.setTimestamp(5,new Timestamp(toSqlDate.getTime()));
301             st.setInt(6, 0);
302             st.setString(7,"3");
303             st.setString(8, "234");
304             st.setString(9, "34");
305             st.setString(10, junctionID);
306             st.execute();
307             st.close();
308         } catch (SQLException e) {
309             e.printStackTrace();
310         }
311     }
312 
313     /**
314      * This method retrieves deviation indices per vehicle ID
315      * @param vehicleID - ID of the vehicle of which deviation index
316      * @return list of deviation indices
317      */
318     public static ArrayList<DeviationIndex> getDeviationIndices(String vehicleID)
319     {
320         String getDevIndx = "select PRIMARYPREF,SECONDARYPREF,CNT,INDXVAL,VEHICLEID,VAL FROM DEVINDX where vehicleID='"+vehicleID+"'";
321         ResultSet rsDevIndx = null;
322         DeviationIndex devIndx = new DeviationIndex();
323         ArrayList<DeviationIndex> devIndxList = new ArrayList<DeviationIndex>();
324       try {
325                 PreparedStatement st = null;
326                 st =  QueueManager.getConnection().prepareStatement(getDevIndx);
327                 rsDevIndx = st.executeQuery();
328                 while(rsDevIndx.next()){
329                     devIndx = new DeviationIndex();
330                     devIndx.setPriPref(rsDevIndx.getString(1));
331                     devIndx.setSecPref(rsDevIndx.getString(2));
332                     devIndx.setCnt(rsDevIndx.getInt(3));
333                     devIndx.setIndxVal(rsDevIndx.getString(4));
334                     devIndx.setVehicleID(rsDevIndx.getString(5));
335                     devIndx.setVal(rsDevIndx.getFloat(6));
336                     devIndxList.add(devIndx);
337                 }
338                 st.close();
339             } catch (SQLException e) {
340                 e.printStackTrace();
341             }
342             return devIndxList;
343     }
344     
345     /**
346      * This method is used to retrive the segment capacity
347      * @param whichEnd - source or destination end
348      * @param segmentID - ID of road segment
349      * @return map of the segments with road capacity
350      */
351     public static synchronized HashMap getAlternateSegmentCap(String whichEnd,String segmentID)
352     {
353         HashMap altRoads = new HashMap();
354         String selectjunctionID = null;
355         if(whichEnd!=null && whichEnd.equals("src"))
356              selectjunctionID =  "select junctionID FROM roadJunction where junctioncoordinates in (select sourcecoordinates from roadsegment where SEGMENTID='"+segmentID+"')";
357         else if(whichEnd!=null && whichEnd.equals("dest"))
358             selectjunctionID =  "select junctionID FROM roadJunction where junctioncoordinates in (select destcoordinates from roadsegment where SEGMENTID='"+segmentID+"')";
359 
360         ArrayList altSegList = getAlternateRoutesFromJunction(selectjunctionID);
361 
362         Iterator iter = altSegList.iterator();
363         while(iter!=null && iter.hasNext())
364         {
365             String seg = (String)iter.next();
366             int cap = getRoadCapacity(seg);
367             altRoads.put(seg, cap);
368         }
369 
370 
371         return altRoads;
372     }
373     
374     
375     public static String getPreviousAdjoiningRoadSegment(String vehicleID,String RIQ)
376     {
377         String vehiclePath =  getVehiclePath(vehicleID);
378         StringTokenizer st = new StringTokenizer(vehiclePath,",");
379         String temp = null;
380         String RIQPath = null;
381         while(st.hasMoreTokens()){
382             RIQPath = st.nextToken();
383             if(RIQPath!=null && RIQPath.equals(RIQ))
384             {
385                 break;
386             }
387             temp = new String(RIQPath);
388         }
389 
390         return temp;
391     }
392 
393     public static synchronized ConcurrentHashMap<String,Double> getLengthOfAssignedRoutes(ConcurrentHashMap roads)
394     {
395         Set entries = roads.entrySet();
396         String assgnedRoute = null;
397         ConcurrentHashMap routeAssgnNumber = new ConcurrentHashMap();
398         if(entries!=null && !entries.isEmpty()){
399         for(Iterator it = entries.iterator(); it.hasNext();) {
400              Map.Entry entry = (Entry) it.next();
401              String agentName =  (String) entry.getKey().toString();
402              assgnedRoute=  (String)(entry.getValue());
403              String selectSegFlow = "select Length from segmentFlow where path='"+assgnedRoute+"'";
404                 ResultSet rsSelect = null;
405                 String srcSeg = null,destSeg=null;
406                 double length = 0.0;
407                 try
408                 {
409                     PreparedStatement st = null;
410                     st =  QueueManager.getConnection().prepareStatement(selectSegFlow);
411                     rsSelect = st.executeQuery();
412                     while(rsSelect.next())
413                     {
414                         length = rsSelect.getDouble(1);
415 
416                         pathLengthMap.put(assgnedRoute, length);
417 
418                     }
419 
420                 }catch (SQLException e) {
421                     e.printStackTrace();
422                 }
423         }
424         }
425         return pathLengthMap;
426 
427     }
428 
429 
430     public static double getOccupancyRate(String vID,String pRIQ)
431     {
432         String path = getVehiclePath(vID);
433         String selectSegFlow = "select srcSeg,destSeg,occupancyRate from segmentFlow where VehicleID='"+vID+"' AND destSeg='"+pRIQ+"'";
434         ResultSet rsSelect = null;
435         String srcSeg = null,destSeg=null;
436         double rate = 0.0;
437         try
438         {
439             PreparedStatement st = null;
440             st =  QueueManager.getConnection().prepareStatement(selectSegFlow);
441             rsSelect = st.executeQuery();
442             while(rsSelect.next())
443             {
444                 srcSeg = rsSelect.getString(1);
445                 destSeg = rsSelect.getString(2);
446                 rate = rsSelect.getDouble(3);
447                 if(path!=null && path.indexOf(srcSeg+","+destSeg)>-1){
448 
449                     return rate;
450                 }
451 
452             }
453 
454         }catch (SQLException e) {
455             e.printStackTrace();
456         }
457         return rate;
458     }
459 
460     public static MssgExchgStepOne getMssgStepOne(String vehicleID,String commStr)
461     {
462         MssgExchgStepOne mssgOne = new MssgExchgStepOne(vehicleID,commStr);
463 
464         ArrayList<DeviationIndex> devIndx = getDeviationIndices(vehicleID);
465         mssgOne.setVehCPR(devIndx);
466 
467         String selectDest = " select destinationCoordinates from journey where journeyId in (select journeyID from VehicleAgent where vehicleID = '"+vehicleID+"')";
468         ResultSet rsSelectDest = null;
469         ArrayList<String> segmentList = new ArrayList<String>();
470         String dest = null;
471         try {
472             PreparedStatement st = null;
473             st =  QueueManager.getConnection().prepareStatement(selectDest);
474             rsSelectDest = st.executeQuery();
475 
476             if(rsSelectDest!=null)
477             {
478                 while(rsSelectDest.next())
479                 {
480                     dest = rsSelectDest.getString(1);
481 
482                 }
483             }
484             st.close();
485         } catch (SQLException e) {
486             e.printStackTrace();
487         }
488         mssgOne.setDest(dest);
489 
490 
491         //retrieving ARC for RIQ
492         HashMap routeRIQ = new HashMap();
493 
494         //new
495         NotificationPattern notifPattern = checkPathForRIQ(vehicleID,0.0);
496         if(notifPattern!=null){
497         mssgOne.setSegmentID(notifPattern.getSegmentID());
498         mssgOne.setReasonForCongestion(notifPattern.getReasonForCongestion());
499         }
500         //new
501         return mssgOne;
502     }
503     
504     /**
505      * This method is used to retrieve road segment capacity of the segment
506      * @param pathRIQ road segment of ehich capacity and length is to be retrieved
507      * @return road capacity
508      */
509     public static int getRoadCapacity(String pathRIQ)
510     {
511 
512         int cnt = 0;
513         String selectRoadCap  = "";
514 
515         if(pathRIQ!=null && pathRIQ.indexOf(",")>-1){
516 
517             StringTokenizer st = new StringTokenizer(pathRIQ,",");
518             if(st!=null){
519                 while(st.hasMoreTokens()){
520                     if(cnt>=1){
521                         selectRoadCap = selectRoadCap+",";
522                     }
523 
524                     selectRoadCap = selectRoadCap+"'"+st.nextToken()+"'";
525                     cnt++;
526                 }
527             }
528             selectRoadCap = "select capacity,length from roadsegment where segmentID in ("+ selectRoadCap + ") order by capacity";
529 
530         }
531         else{
532         selectRoadCap = "select capacity,length from roadsegment where segmentID = '" + pathRIQ + "' order by capacity ";
533         }
534         ResultSet rsCap = null;
535         int roadCapacity=0,rdCap=0/*100*/;
536         double roadLength=0.0;
537         if(pathRIQ!=null && pathRIQ.length()>0){
538         try
539         {
540             PreparedStatement st = null;
541         //  System.out.println("road capacity statement.."+selectRoadCap);
542             st = QueueManager.getConnection().prepareStatement(selectRoadCap);
543             rsCap = st.executeQuery();
544             if(rsCap!=null){
545             while(rsCap.next())
546             {
547                     roadCapacity = rsCap.getInt(1);
548                     roadLength = rsCap.getDouble(2);
549 
550                     if(rdCap<roadCapacity){
551                         rdCap = roadCapacity;
552                     }
553 
554 
555 
556             }
557             }
558             st.close();
559         } catch (SQLException e) {
560         
561             e.printStackTrace();
562         }
563         }
564             return rdCap;
565     }
566 
567     
568     public synchronized static String getPrimaryPreference(String vehString)
569     {
570         String selPriPref = "select primaryPref from devIndx where vehicleID= '"+vehString+"'";
571         ResultSet rsPref = null;
572         String pref = null;
573         try
574         {
575             PreparedStatement st = null;
576             st = QueueManager.getConnection().prepareStatement(selPriPref);
577             rsPref = st.executeQuery();
578             while(rsPref!=null && rsPref.next())
579             {
580             pref = rsPref.getString(1);
581             }
582             st.close();
583         } catch (SQLException e) {
584             e.printStackTrace();
585         }
586 
587         return pref;
588     }
589     public synchronized static String getSecondaryPreference(String vehString, String priPref)
590     {
591         double[] devIndx = new double[2];
592         if(priPref!=null && priPref.equals(Constants.SHORTEST_TIME))
593         {
594             devIndx[0]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_TIME,Constants.SHORTEST_DIST);
595             devIndx[1]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_TIME,Constants.ROUTE_FAMILIARITY);
596             if(devIndx[0]<devIndx[1])
597                 return Constants.SHORTEST_DIST;
598             else
599                 return Constants.ROUTE_FAMILIARITY;
600         }else if(priPref!=null && priPref.equals(Constants.SHORTEST_DIST))
601         {
602             devIndx[0]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_DIST,Constants.SHORTEST_TIME);
603             devIndx[1]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_DIST,Constants.ROUTE_FAMILIARITY);
604             if(devIndx[0]<devIndx[1])
605                 return Constants.SHORTEST_TIME;
606             else
607                 return Constants.ROUTE_FAMILIARITY;
608         }else
609         {
610             devIndx[0]= DataAccess.getDeviationIndicesByPref(vehString,Constants.ROUTE_FAMILIARITY,Constants.SHORTEST_TIME);
611             devIndx[1]= DataAccess.getDeviationIndicesByPref(vehString,Constants.ROUTE_FAMILIARITY,Constants.SHORTEST_DIST);
612             if(devIndx[0]<devIndx[1])
613                 return Constants.SHORTEST_TIME;
614             else
615                 return Constants.SHORTEST_DIST;
616         }
617     }
618 
619     public synchronized static double[] getDIForSecondaryPreferences(String vehString, String priPref)
620     {
621         double[] devIndx = new double[2];
622         if(priPref!=null && priPref.equals(Constants.SHORTEST_TIME))
623         {
624             devIndx[0]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_TIME,Constants.SHORTEST_DIST);
625             devIndx[1]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_TIME,Constants.ROUTE_FAMILIARITY);
626             return devIndx;
627         }else if(priPref!=null && priPref.equals(Constants.SHORTEST_DIST))
628         {
629             devIndx[0]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_DIST,Constants.SHORTEST_TIME);
630             devIndx[1]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_DIST,Constants.ROUTE_FAMILIARITY);
631             return devIndx;
632         }else
633         {
634             devIndx[0]= DataAccess.getDeviationIndicesByPref(vehString,Constants.ROUTE_FAMILIARITY,Constants.SHORTEST_TIME);
635             devIndx[1]= DataAccess.getDeviationIndicesByPref(vehString,Constants.ROUTE_FAMILIARITY,Constants.SHORTEST_DIST);
636             return devIndx;
637         }
638     }
639 
640     public static double chooseDI(String vehString, String priPref, int trafficNature)
641     {
642         double[] devIndx = new double[2];
643         double grtIndx = 0, smIndx = 0;
644 
645         if(priPref!=null && priPref.equals(Constants.SHORTEST_TIME)){
646             devIndx[0]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_TIME,Constants.SHORTEST_DIST);
647             devIndx[1]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_TIME,Constants.ROUTE_FAMILIARITY);
648             }
649         else if(priPref!=null && priPref.equals(Constants.SHORTEST_DIST))
650         {
651             devIndx[0]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_DIST,Constants.SHORTEST_TIME);
652             devIndx[1]= DataAccess.getDeviationIndicesByPref(vehString,Constants.SHORTEST_DIST,Constants.ROUTE_FAMILIARITY);
653 
654         }else
655         {
656             devIndx[0]= DataAccess.getDeviationIndicesByPref(vehString,Constants.ROUTE_FAMILIARITY,Constants.SHORTEST_TIME);
657             devIndx[1]= DataAccess.getDeviationIndicesByPref(vehString,Constants.ROUTE_FAMILIARITY,Constants.SHORTEST_DIST);
658 
659         }
660 
661         if(devIndx[0] > devIndx[1])
662         {
663             grtIndx = devIndx[0];
664             smIndx = devIndx[1];
665         }
666 
667         switch(trafficNature){
668         case Constants.CAP_LESS_THAN_VEH :
669                     return grtIndx;
670         case Constants.VEH_LESS_THAN_CAP :
671             return smIndx;
672         }
673         return smIndx;
674     }
675 
676     public static synchronized String getNatureOfRIQRoute(String route, String vehicleID)
677     {
678         String str = "select path from route where srccrd = '400.0,300.0' and destcrd='500.0,200.0' order by TT";
679         ResultSet rsSelectAltPath = null;
680         String vehPath = null;
681         String roadType = null;
682         try
683         {
684             PreparedStatement st = null;
685             st = QueueManager.getConnection().prepareStatement(str);
686             rsSelectAltPath = st.executeQuery();
687 
688             while(rsSelectAltPath!=null && rsSelectAltPath.next())
689             {
690             vehPath = rsSelectAltPath.getString(1);
691             if(vehPath!=null && vehPath.equals(route)){
692                 roadType =  "ST";
693             break;
694             }
695             }
696             st.close();
697 
698 
699 
700         } catch (SQLException e) {
701             e.printStackTrace();
702         }
703         str = "select path from route where srccrd = '400.0,300.0' and destcrd='500.0,200.0' order by TD";
704         rsSelectAltPath = null;
705 
706         vehPath = null;
707         try
708         {
709             PreparedStatement st = null;
710             st = QueueManager.getConnection().prepareStatement(str);
711             rsSelectAltPath = st.executeQuery();
712 
713             while(rsSelectAltPath!=null && rsSelectAltPath.next())
714             {
715             vehPath = rsSelectAltPath.getString(1);
716             if(vehPath!=null && vehPath.equals(route)){
717                 roadType = "SD";
718 
719                 break;
720             }
721             }
722             st.close();
723 
724 
725 
726         } catch (SQLException e) {
727             e.printStackTrace();
728         }
729 
730         if(vehicleID!=null)
731         {
732             String selPath = "select path from route where pathID in (select pathID from fdevindx where vehicleID='"+vehicleID+"'"+"order by findx DESC) and destcrd='500.0,200.0'";
733             rsSelectAltPath = null;
734 
735             vehPath = null;
736             try
737             {
738                 PreparedStatement st = null;
739                 st = QueueManager.getConnection().prepareStatement(str);
740                 rsSelectAltPath = st.executeQuery();
741 
742                 while(rsSelectAltPath!=null && rsSelectAltPath.next())
743                 {
744                 vehPath = rsSelectAltPath.getString(1);
745                 if(vehPath!=null && vehPath.equals(route)){
746                     roadType = "F";
747                 }
748                 break;
749                 }
750                 st.close();
751 
752 
753 
754             } catch (SQLException e) {
755                 e.printStackTrace();
756             }
757         }
758 
759         System.out.println("RoadType"+roadType);
760         return roadType;
761 
762     }
763 
764 
765     public static synchronized ArrayList<String> getAlternatePathsOrderByTT(String vehString,String thisPath,HashMap pthCntMap,boolean conditionalFlag)
766     {
767         String selAltPath = "select path,TT,srccrd,destcrd from route where srccrd in (select sourcecoordinates from journey where journeyID in (select journeyID from vehicleagent where vehicleID='"+vehString+"'))  and destcrd='480,0' order by TT";
768         double travelTime = 0.0,firstTravelTime=0.0;
769         ResultSet rsSelectAltPath = null;
770         ArrayList<String> altPathList = new ArrayList<String>();
771         ArrayList<String> altPathListOther = new ArrayList<String>();
772         String vehPath = null;
773         boolean firstElem = true;
774         double timeTolerance = getSTToleranceVal(vehString);
775         try
776         {
777             PreparedStatement st = null;
778             st = QueueManager.getConnection().prepareStatement(selAltPath);
779             rsSelectAltPath = st.executeQuery();
780             while(rsSelectAltPath!=null && rsSelectAltPath.next())
781             {
782             vehPath = rsSelectAltPath.getString(1);
783             travelTime = rsSelectAltPath.getDouble(2);
784             if(firstElem){
785                 firstTravelTime = travelTime;
786                 firstElem = false;
787             }if(conditionalFlag){
788                 if(travelTime-firstTravelTime < timeTolerance){
789                     altPathList.add(vehPath);
790                 }
791             }else{
792             altPathList.add(vehPath);
793             }
794             }
795             st.close();
796             //Get the most preferred shortest time path next in sequence after 'thisPath'
797             int cnt = 0;
798             if(thisPath!=null)
799             {
800                 Iterator iter = altPathList.iterator();
801                 while(iter.hasNext())
802                 {
803                     String path = (String)iter.next();
804                     if(path!=null && path.indexOf(thisPath)>-1)
805                     {
806                         continue;
807                     }else
808                     {
809                         if(reachedPathCount(path,pthCntMap)){
810                             continue;
811                         }
812                         else
813                         altPathListOther.add(path);
814 
815                     }
816                 }
817                 return altPathListOther;
818             }
819 
820         } catch (SQLException e) {
821             e.printStackTrace();
822         }
823 
824         return altPathList;
825     }
826 
827     
828     
829      public static synchronized boolean reachedPathCount(String path,HashMap pathCntMap)
830         {
831             Set entries = pathCntMap.entrySet();
832             String ag  = null;
833             int pathCnt = 0;
834             String src = "src";
835             synchronized(pathCntMap){
836             if(entries!=null && !entries.isEmpty()){
837             for(Iterator it = entries.iterator(); it.hasNext();) {
838                  Map.Entry entry = (Entry) it.next();
839                  String aPath =  (String) entry.getKey().toString();
840                  if(aPath!=null && aPath.equals(path))
841                   {
842                      pathCnt =  Integer.parseInt(entry.getValue().toString());
843                     // System.out.println("prining pathcnt "+pathCnt+"for path : "+path);
844                      if(pathCnt > DataAccess.getRoadCapacity(aPath))
845                          return false;
846                      else
847                          return true;
848                   }
849             }
850             }
851             }
852             return false;
853         }
854 
855 
856     /**
857      * This method retrieves deviation indices by preferences
858      * vehicleID - ID of the vehicle
859      * pref - primary preference
860      * secPref - secondary preference
861      */
862     public static synchronized double getDeviationIndicesByPref(String vehicleID,String pref, String secPref)
863     {
864         String getDevIndx = "select VAL FROM DEVINDX where vehicleID='"+vehicleID+"' AND PRIMARYPREF = '"+pref+"' AND SECONDARYPREF='"+secPref+"'" ;
865         ResultSet rsDevIndx = null;
866         double devIndx = 0.0;
867 
868       try {
869                 PreparedStatement st = null;
870                 System.out.println("Printing SQL..."+getDevIndx);
871                 st =  QueueManager.getConnection().prepareStatement(getDevIndx);
872                 rsDevIndx = st.executeQuery();
873                 while(rsDevIndx.next()){
874                     devIndx = rsDevIndx.getDouble(1);
875                 }
876                 st.close();
877             } catch (SQLException e) {
878                 e.printStackTrace();
879             }
880 
881             return devIndx;
882     }
883 
884     /**
885      * This method retrieves the initial position of the vehicle
886      * @param vID ID of the vehicle
887      * @return initial position
888      */
889     public static synchronized Position3D getInitialPosition(String vID)
890     {
891         String getDevIndx = "select sourcecoordinates from journey where journeyId in (select journeyID from VehicleAgent where vehicleID='"+vID+"')";
892         ResultSet rsDevIndx = null;
893         String srcCrd = null;
894         String xCoord = null;
895         String yCoord = null;
896         String temp = null;
897         Position3D ps = null;
898       try {
899                 PreparedStatement st = null;
900                 st =  QueueManager.getConnection().prepareStatement(getDevIndx);
901                 rsDevIndx = st.executeQuery();
902                 while(rsDevIndx.next()){
903                     srcCrd = rsDevIndx.getString(1);
904                 }
905                 st.close();
906             //    System.out.println("src "+srcCrd+" for "+vID);
907                 StringTokenizer vSt = new StringTokenizer(srcCrd,",");
908                 while(vSt.hasMoreTokens())
909                 {
910                     if(temp==null)
911                         xCoord  = vSt.nextToken();
912                     else
913                         yCoord = vSt.nextToken();
914                     temp = new String(xCoord);
915                 }
916 
917                 ps = new Position3D("vID",new Double(xCoord),new Double(yCoord),0.0);
918 
919             } catch (SQLException e) {
920                 e.printStackTrace();
921             }
922             return ps;
923     }
924 
925     /**
926      * This method retrieves the destination position of the vehicle ID
927      * @param vID ID of the vehicle
928      * @return destination position
929      */
930     public static Position3D getDestinationPosition(String vID)
931     {
932         String getDevIndx = "select destinationcoordinates from journey where journeyId in (select journeyID from VehicleAgent where vehicleID='"+vID+"')";
933         ResultSet rsDevIndx = null;
934         String destCrd = null;
935         String xCoord = null;
936         String yCoord = null;
937         String temp = null;
938         Position3D ps = null;
939       try {
940                 PreparedStatement st = null;
941                 st =  QueueManager.getConnection().prepareStatement(getDevIndx);
942                 rsDevIndx = st.executeQuery();
943                 while(rsDevIndx.next()){
944                     destCrd = rsDevIndx.getString(1);
945                 }
946                 st.close();
947                 if(destCrd!=null){
948                 StringTokenizer vSt = new StringTokenizer(destCrd,",");
949                 while(vSt.hasMoreTokens())
950                 {
951                     if(temp==null)
952                         xCoord  = vSt.nextToken();
953                     else
954                         yCoord = vSt.nextToken();
955                     temp = new String(xCoord);
956                 }
957 
958                 ps = new Position3D("vID",new Double(xCoord),new Double(yCoord),0.0);
959                 }
960 
961             } catch (SQLException e) {
962                 e.printStackTrace();
963             }
964 
965       return ps;
966     }
967 
968     /**
969      * This method retrieves segment ID based on initial and destination position
970      * @param initPos initial position
971      * @param destpos destination position
972      * @return segment ID
973      */
974     public static synchronized String getSegmentID(Position3D initPos, Position3D destpos)
975     {
976         String getDevIndx = "select segmentID FROM roadsegment where sourcecoordinates=? and destcoordinates=?";
977         ResultSet rsDevIndx = null;
978         String srcCrd = null;
979         String destCrd = null;
980         String segID= null;
981         Position3D ps = null;
982         if(initPos!=null && destpos!=null){
983       try {
984                 PreparedStatement st = null;
985                 st =  QueueManager.getConnection().prepareStatement(getDevIndx);
986 
987                 srcCrd = initPos.getX()+","+initPos.getY();
988                 destCrd = destpos.getX()+","+destpos.getY();
989                 st.setString(1, srcCrd);
990                 st.setString(2,destCrd);
991                 rsDevIndx = st.executeQuery();
992                 while(rsDevIndx.next()){
993                     segID = rsDevIndx.getString(1);
994                 }
995 
996             } catch (SQLException e) {
997                 e.printStackTrace();
998             }
999         }
1000            return segID;
1001    }
1002
1003    private static synchronized boolean checkVehRecord(String vehID)
1004    {
1005        String addVehPath = "SELECT VEHICLEPATH FROM TEMPVEHPATH where VEHICLEID='"+vehID+"'";
1006
1007        try {
1008
1009                PreparedStatement st = null;
1010                st =  QueueManager.getConnection().prepareStatement(addVehPath);
1011                ResultSet rs = st.executeQuery();
1012                if(rs!=null && rs.getFetchSize()==0)
1013                {
1014                    st.close();
1015                    return false;
1016                }else{
1017                    st.close();
1018                    return true;
1019                }
1020
1021
1022            } catch (SQLException e) {
1023                // TODO Auto-generated catch block
1024                e.printStackTrace();
1025            }
1026        return false;
1027    }
1028
1029public static double recordDriverCompliance(String vehID) {
1030
1031        String getDevIndx = "select compliancedegree from vehicleAgent where vehicleID='"+vehID+"'";
1032        String saveCompDegree = "update vehicleAgent set compliancedegree=? where vehicleID='"+vehID+"'";
1033        ResultSet rs = null;
1034        double compDegree = 0.0,updatedCompDegree=0.0;
1035        int numOfAgtCCNS = 0;
1036        String assgRoute = null;
1037
1038      try {
1039                PreparedStatement st = null;
1040                Connection con = QueueManager.getConnection();
1041                st =  con.prepareStatement(getDevIndx);
1042                rs = st.executeQuery();
1043                while(rs!=null && rs.next())
1044                {
1045                compDegree = rs.getDouble(1);
1046              //  numOfAgtCCNS = rs.getInt(2);
1047              //  assgRoute = rs.getString(3);
1048                }
1049
1050                st.clearParameters();
1051                if(compDegree==1.0){
1052                    updatedCompDegree=0.5;
1053                }else if(compDegree == 0.5){
1054                    updatedCompDegree=0.0;
1055                }
1056                st =  con.prepareStatement(saveCompDegree);
1057                st.setDouble(1,updatedCompDegree);
1058                st.executeUpdate();
1059
1060                st.close();
1061            } catch (SQLException e) {
1062                e.printStackTrace();
1063            }
1064
1065        return compDegree;
1066    }
1067
1068/**
1069 * This method is used to retrieve travel time of the route under consideration
1070 * @param pathID Id of the route
1071 * @return travel time
1072 */
1073public synchronized static double getRouteTT(String pathID)
1074{
1075
1076    ResultSet rs = null;
1077    String route = null;
1078    double travelTime=0;
1079
1080    int pID = Integer.parseInt(pathID);
1081
1082
1083
1084
1085    String getTravelTime = "select TT from route where pathID="+pID;
1086  try {
1087            PreparedStatement st = null;
1088            Connection con = QueueManager.getConnection();
1089            st =  con.prepareStatement(getTravelTime);
1090            rs = st.executeQuery();
1091            while(rs!=null && rs.next())
1092            {
1093            travelTime = rs.getInt(1);
1094
1095            }
1096
1097
1098            st.close();
1099        } catch (SQLException e) {
1100            e.printStackTrace();
1101        }
1102        return travelTime;
1103}
1104
1105/**
1106 * This method retrieves the travel distance of the path under consideration
1107 * @param pathID ID of the route
1108 * @return travel distance
1109 */
1110public static synchronized double getRouteTD(String pathID)
1111{
1112
1113    String route = null;
1114
1115    int pID = Integer.parseInt(pathID);
1116
1117    String getTravelTime = "select TD from route where pathID="+pID;
1118
1119    ResultSet rs = null;
1120    double travelDistance=0;
1121
1122  try {
1123            PreparedStatement st = null;
1124            Connection con = QueueManager.getConnection();
1125            st =  con.prepareStatement(getTravelTime);
1126            rs = st.executeQuery();
1127            while(rs!=null && rs.next())
1128            {
1129                travelDistance = rs.getInt(1);
1130            }
1131            st.close();
1132        } catch (SQLException e) {
1133            e.printStackTrace();
1134        }
1135        return travelDistance;
1136}
1137
1138public static  synchronized TreeMap getRIQRoutesByTTAsc(String pathRIQ)
1139{
1140    String getTravelTime = "select path,TT from route where path like '%"+pathRIQ+"%' and srccrd='300.0,200.0' and destcrd='500.0,200.0' order by TT ASC";
1141    ResultSet rs = null;
1142
1143    bvcRIQ =  new ValueComparator(RIQMap);
1144
1145
1146  try {
1147            PreparedStatement st = null;
1148            Connection con = QueueManager.getConnection();
1149            st =  con.prepareStatement(getTravelTime);
1150            rs = st.executeQuery();
1151
1152            while(rs!=null && rs.next())
1153            {
1154                String path = rs.getString(1);
1155                double time = rs.getDouble(2);
1156                //System.out.println("path:"+path+" and time is "+time);
1157                RIQMap.put(path,time);
1158            }
1159
1160            sortedWeightMapRIQ.putAll(RIQMap);
1161            st.close();
1162        } catch (SQLException e) {
1163            e.printStackTrace();
1164        }
1165        return sortedWeightMapRIQ;
1166}
1167
1168public static synchronized double getTTOfShortestRoute(String path)
1169{
1170    travelTime =  getRouteTT(path);
1171    return travelTime;
1172}
1173
1174/**
1175 * This method is used to retrieve ST tolerance value for the given vehicle ID
1176 * @param vID ID of the vehicle
1177 * @return ST tolerance value
1178 */
1179public static synchronized double getSTToleranceVal(String vID)
1180{
1181    String getTravelTime = "select STTolerance from vehicleAgent where vehicleID= '"+vID+"'";
1182    ResultSet rs = null;
1183    double stTolerance = 0.0;
1184  try {
1185            PreparedStatement st = null;
1186            Connection con = QueueManager.getConnection();
1187            st =  con.prepareStatement(getTravelTime);
1188            rs = st.executeQuery();
1189
1190            while(rs!=null && rs.next())
1191            {
1192                stTolerance = rs.getDouble(1);
1193            }
1194            st.close();
1195        } catch (SQLException e) {
1196            e.printStackTrace();
1197        }
1198        return stTolerance;
1199}
1200
1201/**
1202 * This method is used to retieve SD tolerance value of the vehicle
1203 * @param vID vehicle ID
1204 * @return SD tolerance value
1205 */
1206public static synchronized double getSDToleranceVal(String vID)
1207{
1208    String getTravelDist = "select SDTolerance from vehicleAgent where vehicleID= '"+vID+"'";
1209    ResultSet rs = null;
1210    double sdTolerance = 0.0;
1211  try {
1212            PreparedStatement st = null;
1213            Connection con = QueueManager.getConnection();
1214            st =  con.prepareStatement(getTravelDist);
1215            rs = st.executeQuery();
1216
1217            while(rs!=null && rs.next())
1218            {
1219                sdTolerance = rs.getDouble(1);
1220            }
1221            st.close();
1222        } catch (SQLException e) {
1223            e.printStackTrace();
1224        }
1225        return sdTolerance;
1226}
1227
1228public static synchronized void addNotifPattern(String localName, String key, int res) {
1229
1230
1231    if(!checkNotifPatternExists(localName,key)){
1232
1233        String addNotifPattern = "INSERT INTO NOTIFICATIONPATTERN(SEGMENTID,REASONFORCONGESTION,VEHICLEID) VALUES('"+key+"',"+res+",'"+localName+"')";
1234        try {
1235
1236                PreparedStatement st = null;
1237                st =  QueueManager.getConnection().prepareStatement(addNotifPattern);
1238                st.execute();
1239                st.close();
1240            } catch (SQLException e) {
1241                // TODO Auto-generated catch block
1242                e.printStackTrace();
1243            }
1244
1245
1246        }
1247
1248
1249}
1250
1251private static synchronized boolean checkNotifPatternExists(String vehicleID,String RIQ) {
1252    String selectNotifPattern = "select segmentID from notificationpattern where vehicleID='"+vehicleID+"' and segmentID='"+RIQ+"' ";
1253
1254    try {
1255
1256        PreparedStatement st = null;
1257        st =  QueueManager.getConnection().prepareStatement(selectNotifPattern);
1258        ResultSet rs = st.executeQuery();
1259        if(rs!=null){
1260            while(rs.next())
1261            {
1262                return true;
1263            }
1264        }
1265
1266
1267    } catch (SQLException e) {
1268        // TODO Auto-generated catch block
1269        e.printStackTrace();
1270    }
1271    return false;
1272}
1273
1274public static synchronized void updateOccRate(String vehID,String srcSeg,String destSeg)
1275{
1276    String insertOccRate = "insert into segmentFlow(vehicleID,srcSeg,destSeg) values('"+vehID+"','"+srcSeg+"','"+destSeg+"')";
1277    try {
1278
1279        PreparedStatement st = null;
1280        System.out.println(insertOccRate);
1281        st =  QueueManager.getConnection().prepareStatement(insertOccRate);
1282        st.execute();
1283        st.close();
1284    } catch (SQLException e) {
1285        // TODO Auto-generated catch block
1286        e.printStackTrace();
1287    }
1288}
1289
1290/**
1291 * This method is used to retrive source coordinates of a segment ID
1292 * @param segID segment ID
1293 * @param type type of coordinates
1294 * @return source coordinates
1295 */
1296public static synchronized String getSourceCoordinates(String segID,String type)
1297{
1298    String getSrc = "select sourcecoordinates from roadsegment where segmentID='"+segID+"'";
1299    String coordinates = null;
1300try {
1301
1302        PreparedStatement st = null;
1303        st =  QueueManager.getConnection().prepareStatement(getSrc);
1304        ResultSet rs = st.executeQuery();
1305        if(rs!=null){
1306            while(rs.next())
1307            {
1308                coordinates = rs.getString(1);
1309                StringTokenizer token = new StringTokenizer(coordinates,",");
1310                while(token.hasMoreTokens()){
1311                    coordinates = token.nextToken();
1312                    if(type!=null&&type.equals("x"))
1313                    break;
1314                }
1315
1316            }
1317        }
1318        st.close();
1319
1320    } catch (SQLException e) {
1321        // TODO Auto-generated catch block
1322        e.printStackTrace();
1323    }
1324
1325return coordinates;
1326}
1327
1328/**
1329 * This method is used to retrieve destination coordinates of the segment ID
1330 * @param segID Id of the segment
1331 * @param type type of coordinate
1332 * @return destination coordinates
1333 */
1334public static synchronized String getDestCoordinates(String segID,String type)
1335{
1336    String getSrc = "select destcoordinates from roadsegment where segmentID='"+segID+"'";
1337    String coordinates = null;
1338try {
1339
1340        PreparedStatement st = null;
1341        st =  QueueManager.getConnection().prepareStatement(getSrc);
1342        ResultSet rs = st.executeQuery();
1343        if(rs!=null){
1344            while(rs.next())
1345            {
1346                coordinates = rs.getString(1);
1347                StringTokenizer token = new StringTokenizer(coordinates,",");
1348                while(token.hasMoreTokens()){
1349                    coordinates = token.nextToken();
1350                    if(type!=null&&type.equals("x"))
1351                    break;
1352                }
1353
1354            }
1355        }
1356
1357        st.close();
1358    } catch (SQLException e) {
1359        // TODO Auto-generated catch block
1360        e.printStackTrace();
1361    }
1362
1363return coordinates;
1364}
1365public static synchronized String getNewSourceCoordinates(String segID)
1366{
1367    String getSrc = "select sourcecoordinates from roadsegment where segmentID='"+segID+"'";
1368    String coordinates = null;
1369try {
1370
1371        PreparedStatement st = null;
1372        st =  QueueManager.getConnection().prepareStatement(getSrc);
1373        ResultSet rs = st.executeQuery();
1374        if(rs!=null){
1375            while(rs.next())
1376            {
1377                coordinates = rs.getString(1);
1378            }
1379        }
1380        st.close();
1381
1382    } catch (SQLException e) {
1383        e.printStackTrace();
1384    }
1385
1386return coordinates;
1387}
1388
1389public static synchronized String getNewDestCoordinates(String segID,String type)
1390{
1391    String getSrc = "select destcoordinates from roadsegment where segmentID='"+segID+"'";
1392    String coordinates = null;
1393try {
1394
1395        PreparedStatement st = null;
1396        st =  QueueManager.getConnection().prepareStatement(getSrc);
1397        ResultSet rs = st.executeQuery();
1398        if(rs!=null){
1399            while(rs.next())
1400            {
1401                coordinates = rs.getString(1);
1402
1403            }
1404        }
1405
1406        st.close();
1407    } catch (SQLException e) {
1408    e.printStackTrace();
1409    }
1410
1411return coordinates;
1412}
1413
1414
1415public static double getFamiliarityIndxVal(String vehicleID,String pathID){
1416    int pathIDInt = Integer.parseInt(pathID);
1417    String getIndx = "select findx from fdevindx where pathID=" +pathIDInt+" and vehicleID = '" + vehicleID + "'";
1418    double indx = 0.0;
1419    try {
1420    /*  PreparedStatement st = null;
1421    //  System.out.println("fdevindx "+getIndx);
1422        st =  QueueManager.getConnection().prepareStatement(getIndx);
1423        ResultSet rs = st.executeQuery();
1424        if(rs!=null){
1425            while(rs.next())
1426            {
1427                indx = rs.getDouble(1);
1428
1429
1430            }
1431        }
1432        st.close();*/
1433        Random rand = new Random();
1434        Float randFloat = null;
1435        if(vehicleID!=null){
1436            //2,4,6,8,10,11,13,15,17 are familiar
1437            if(pathID!=null && pathID.equals("24") || pathID.equals("27") || pathID.equals("23") || pathID.equals("2") || pathID.equals("4")|| pathID.equals("6")|| pathID.equals("8")|| pathID.equals("10")|| pathID.equals("11")|| pathID.equals("13")|| pathID.equals("15")|| pathID.equals("17")){
1438            String strCheck="#0,#1,#2,#3,#4,#10,#11,#12,#13,#14,#29,#30,#31,#32,#33,#34,#35,#36,#37,#38,#39,#69,#70,#71,#72,#73,#74,#75,#76,#77,#78,#79,#87,#88,#89";
1439
1440            StringTokenizer st =  new StringTokenizer(strCheck,",");
1441            while(st!=null & st.hasMoreElements()){
1442                String num = (String) st.nextElement();
1443                if(num!=null && num.equals(vehicleID)){
1444                    randFloat = rand.nextFloat();
1445                    if(randFloat<0.5){
1446                        return 0.5;
1447                    }else{
1448                        return randFloat;
1449                    }
1450
1451                }
1452
1453            }
1454            }
1455        }//
1456
1457    } catch (Exception e) {
1458        // TODO Auto-generated catch block
1459        e.printStackTrace();
1460    }
1461
1462return 0.0;
1463}
1464
1465/**
1466 * This method retrieves preference utility weight values of the given vehicle ID
1467 * @param vehicleID ID of the vehicle of which preference utility weight values is to be retrieved
1468 * @param routeUnderConsideration route of the vehicle inder consideration
1469 * @return preference utility weight value
1470 */
1471public static double getPreferenceUtilityWeightValues(String vehicleID,String routeUnderConsideration)
1472{
1473    double prefUtilityWt = 0.0;
1474    ResultSet rs = null;
1475    PreparedStatement st = null;
1476    double TTRouteUC = getRouteTT(routeUnderConsideration);
1477    double TDRouteUC = getRouteTD(routeUnderConsideration);
1478
1479    try {
1480
1481        if((vehicleID.equals("#5") || vehicleID.equals("#6")) /*&& vehicleID.equals("#17")*/ ){
1482//      System.out.println("check wt");
1483        }
1484
1485        if(vehicleID!=null & vehicleID.equals("#0")){
1486    //      System.out.println("%%");
1487        }
1488
1489        //Alternate Route Exists
1490        String getPathID = "select pathID,path from route where srccrd in (select sourcecoordinates from journey where journeyID in (select journeyID from vehicleagent where vehicleID ='"+vehicleID+"')) AND  destcrd in (select destinationcoordinates from journey where journeyID in (select journeyID from vehicleagent where vehicleID ='"+vehicleID+"'))";
1491        int altRoute=0;
1492        String segID = null;
1493        String seg = null;
1494        st =  QueueManager.getConnection().prepareStatement(getPathID);
1495        rs = st.executeQuery();
1496        while(rs!=null && rs.next())
1497        {
1498            segID = rs.getString(1);
1499            seg = rs.getString(2);
1500            altRoute++;
1501        }
1502        if(altRoute>1)
1503            prefUtilityWt = prefUtilityWt+(Constants.ALT_ROUTE_WT_FACTOR*0);
1504        else
1505            prefUtilityWt = prefUtilityWt+(Constants.ALT_ROUTE_WT_FACTOR*1);
1506    //  System.out.println("pref utility wt after alt route consideration "+prefUtilityWt);
1507
1508
1509        //Previous Compliance Factor
1510        String getCompFactor = "select compliancedegree from vehicleagent where vehicleID ='"+vehicleID+"'";
1511        st =  QueueManager.getConnection().prepareStatement(getCompFactor);
1512        rs = st.executeQuery();
1513        double compDegree = 0.0;
1514        while(rs!=null && rs.next())
1515        {
1516
1517            compDegree = rs.getDouble(1);
1518            altRoute++;
1519        }
1520        prefUtilityWt = prefUtilityWt+(compDegree*Constants.PREV_COMPL_FACTOR);
1521//      System.out.println("pref utility wt after prev compl factor "+prefUtilityWt);
1522
1523
1524        //Familiarity Index
1525        double familiarityIndex = getFamiliarityIndxVal(vehicleID, routeUnderConsideration);
1526        prefUtilityWt = prefUtilityWt+(familiarityIndex*Constants.FAMILIARITY_INDX_FACTOR);
1527
1528
1529
1530        //Deviation Index
1531        double deviationIndex = QueueManager.getDeviationIndex(routeUnderConsideration, vehicleID,familiarityIndex);
1532        prefUtilityWt = prefUtilityWt+(deviationIndex*Constants.DEV_INDX_FACTOR);
1533    //  System.out.println("pref utility wt after dev indx "+prefUtilityWt+ " for agent : "+vehicleID+ " for path - "+routeUnderConsideration);
1534
1535
1536        //Time Tolerance
1537        int stToleranceFactor = 0;
1538        double stTolerance = getSTToleranceVal(vehicleID);
1539        if(TTRouteUC<stTolerance)
1540            stToleranceFactor = 1;
1541        else
1542            stToleranceFactor = 0;
1543        prefUtilityWt = prefUtilityWt+(stToleranceFactor*Constants.TIME_TOLERANCE_FACTOR);
1544        //Distance Tolerance
1545        int sdToleranceFactor = 0;
1546        double sdTolerance = getSDToleranceVal(vehicleID);
1547        if(TDRouteUC<sdTolerance)
1548            sdToleranceFactor = 1;
1549        else
1550            sdToleranceFactor = 0;
1551        prefUtilityWt = prefUtilityWt+(sdToleranceFactor*Constants.DIST_TOLERANCE_FACTOR);
1552        st.close();
1553    } catch (SQLException e) {
1554        // TODO Auto-generated catch block
1555        e.printStackTrace();
1556    }
1557
1558    return prefUtilityWt;
1559
1560}
1561
1562/**
1563 * This method is used to classify the preference utility weight into bands and evaluate preference utility index
1564 * @param vehicleID ID of the vehicle of which preference utility weight is to be evaluated
1565 * @param pUIndex preference utility index
1566 * @param preferenceMultiplier preference multiplier
1567 * @param costMultiplier cost multiplier
1568 * @param segmentOnPath segment ID
1569 * @param yCoord y coordinate
1570 * @param cvMaps map of with vehicle information
1571 * @return preference utility indices
1572 */
1573public static synchronized PreferenceUtilityIndex classifyIntoBands(String vehicleID,PreferenceUtilityIndex pUIndex, double preferenceMultiplier, double costMultiplier, String segmentOnPath,String yCoord, CommunicatingVehicles cvMaps)
1574{
1575    if(cvMaps!=null){
1576    routeRankMap = cvMaps.getRouteRankMapForCommID();}
1577    else{
1578    routeRankMap = null;
1579    routeRankMap = new ConcurrentHashMap();
1580    }
1581    String getPreferredPathID = "select pathID from newPreferredRoute where onCongestedPath = '" + segmentOnPath + "'";
1582    String B1="",B2="",B3="",B4="",B5="";
1583    int choiceNum=0;
1584    int b1=0,b2=0,b3=0,b4=0,b5=0;
1585    double val=0.0;
1586    int b1CntInt=0,b2CntInt=0,b3CntInt=0,b4CntInt=0,b5CntInt=0;
1587    pUIndex.setVehicleID(vehicleID);
1588    String preferredPathIDRs = "",preferredPathID="";
1589    double preferenceUtilityWeight = 0.0;
1590    ArrayList prefList = new ArrayList();
1591
1592    try {
1593
1594        if(segmentOnPath!=null && segmentOnPath.equals("s11")){
1595//          System.out.println("check route allocation ");
1596        }
1597
1598        if(vehicleID!=null && (vehicleID.equals("#20") || vehicleID.equals("#23"))){
1599//          System.out.println("#37");
1600        }
1601
1602        if(preferenceMultiplier!=0){
1603        PreparedStatement st = null;
1604        st =  QueueManager.getConnection().prepareStatement(getPreferredPathID);
1605        ResultSet rs = st.executeQuery();
1606        if(rs!=null){
1607            b1=0;b2=0;b3=0;b4=0;b5=0;
1608            while(rs.next())
1609            {
1610
1611
1612                preferredPathIDRs = rs.getString(1);
1613                preferenceUtilityWeight = getPreferenceUtilityWeightValues(vehicleID,preferredPathIDRs);
1614                prefList.add(preferredPathIDRs);
1615
1616                if(preferenceUtilityWeight>=0.8 && preferenceUtilityWeight<=1.0){
1617                    if(B1.equals(""))
1618                        B1=B1+preferredPathIDRs;
1619                    else
1620                        B1=B1+","+preferredPathIDRs;
1621                    Object b1Cnt =  routeRankMap.get(preferredPathIDRs);
1622
1623                    if(b1Cnt!=null){
1624                        b1CntInt  =  Integer.parseInt(b1Cnt.toString())/5;
1625                    }else{
1626                        b1CntInt  =  1;
1627                    }
1628                    if(preferenceMultiplier!=0){
1629                    routeRankMap.put(preferredPathIDRs, 5*(b1CntInt++));
1630                    }
1631                b1++;
1632                }else if(preferenceUtilityWeight>=0.6 && preferenceUtilityWeight<0.8){
1633                    if(B2.equals(""))
1634                        B2=B2+preferredPathIDRs;
1635                    else
1636                        B2=B2+","+preferredPathIDRs;
1637                    Object b2Cnt =  routeRankMap.get(preferredPathIDRs);
1638
1639                    if(b2Cnt!=null){
1640                        b2CntInt  =  Integer.parseInt(b2Cnt.toString())/4;
1641                    }else{
1642                        b2CntInt  =  1;
1643                    }
1644                    b2CntInt++;
1645                    b2CntInt=b2CntInt*4;
1646                    if(preferenceMultiplier!=0){
1647                    routeRankMap.put(preferredPathIDRs, b2CntInt++);
1648                    }
1649                b2++;
1650                }if(preferenceUtilityWeight>=0.4 && preferenceUtilityWeight<0.6){
1651                    if(B3.equals(""))
1652                        B3=B3+preferredPathIDRs;
1653                    else
1654                        B3=B3+","+preferredPathIDRs;
1655                    Object b3Cnt =  routeRankMap.get(preferredPathIDRs);
1656
1657                    if(b3Cnt!=null){
1658                        b3CntInt  =  Integer.parseInt(b3Cnt.toString())/3;
1659                    }else{
1660                        b3CntInt  =  1;
1661                    }
1662                    b3CntInt++;
1663                    b3CntInt=b3CntInt*3;
1664                    if(preferenceMultiplier!=0){
1665                    routeRankMap.put(preferredPathIDRs, b3CntInt++);
1666                    }
1667                b3++;
1668                }if(preferenceUtilityWeight>=0.2 && preferenceUtilityWeight<0.4){
1669                    if(B4.equals(""))
1670                        B4=B4+preferredPathIDRs;
1671                    else
1672                        B4=B4+","+preferredPathIDRs;
1673                    Object b4Cnt =  routeRankMap.get(preferredPathIDRs);
1674
1675                    if(b4Cnt!=null){
1676                        b4CntInt  =  Integer.parseInt(b4Cnt.toString())/2;
1677                    }else{
1678                        b4CntInt  =  1;
1679                    }
1680                    b4CntInt++;
1681                    b4CntInt=b4CntInt*2;
1682                    if(preferenceMultiplier!=0){
1683                    routeRankMap.put(preferredPathIDRs, b4CntInt);
1684                    }
1685                b4++;
1686                }if(preferenceUtilityWeight>=0.0 && preferenceUtilityWeight<0.2){
1687                    if(B5.equals(""))
1688                        B5=B5+preferredPathIDRs;
1689                    else
1690                        B5=B5+","+preferredPathIDRs;
1691                    Object b5Cnt = routeRankMap.get(preferredPathIDRs);
1692
1693                    if(b5Cnt!=null){
1694                        b5CntInt  =  Integer.parseInt(b5Cnt.toString());
1695                    }else{
1696                        b5CntInt  =  1;
1697                    }
1698                    b5CntInt++;
1699                    if(preferenceMultiplier!=0){
1700                    routeRankMap.put(preferredPathIDRs, (b5CntInt));
1701                    }
1702                b5++;
1703                }
1704        st.close();
1705
1706
1707    pUIndex.setB1(B1);
1708    pUIndex.setB2(B2);
1709    pUIndex.setB3(B3);
1710    pUIndex.setB4(B4);
1711    pUIndex.setB5(B5);
1712
1713}//end of while rs -new
1714
1715            Iterator iterPref = prefList.iterator();
1716            while(iterPref!=null && iterPref.hasNext()){
1717                preferredPathID = (String) iterPref.next();
1718            if(preferenceMultiplier!=0 && costMultiplier!=0){
1719            Map sortedRouteMap = sortByComparator(routeRankMap);
1720            ConcurrentHashMap newRoMap = new ConcurrentHashMap();
1721            Set entries = sortedRouteMap.entrySet();
1722            if(entries!=null && !entries.isEmpty()){
1723                int k=1;
1724                for(Iterator it = entries.iterator(); it.hasNext();) {
1725
1726                    boolean unassigned = true;
1727                    Map.Entry entry = (Entry) it.next();
1728                    String route =  (String) entry.getKey();
1729                    newRoMap.put(route, k);
1730                    k++;
1731                }
1732            }
1733
1734
1735            String rtList = "";
1736            int listSize=0,prefWt=0,wt=0;
1737            ConcurrentHashMap tempRoMap = new ConcurrentHashMap();
1738            Object finalWtObj=null;
1739            TreeMap subMap = new TreeMap();
1740            ArrayList paths = getRoutesMatchingPath(segmentOnPath,yCoord);
1741            if(paths!=null){
1742                Iterator iter = paths.iterator();
1743                if(iter!=null){
1744                    int costWt = 1;
1745
1746                    while(iter.hasNext()){
1747                        String rt = (String) iter.next();
1748                        listSize++;
1749                        finalWtObj = newRoMap.get(rt);
1750                        if(finalWtObj!=null){
1751                            prefWt = Integer.parseInt(finalWtObj.toString());
1752                            //System.out.println("for vehicleID.."+vehicleID+" with prefWt "+prefWt+" and cost Wt "+costWt+" for route "+rt);
1753                            costWt++;
1754                            wt=prefWt+costWt;
1755                            tempRoMap.put(rt, wt);
1756                        }else{
1757                            tempRoMap.put(rt, wt);
1758                        }
1759
1760
1761                        if(rtList!=null){
1762                            rtList=rtList.concat(rt);
1763
1764                            if(listSize<paths.size()){
1765                                rtList=rtList.concat(",");
1766                            }
1767                        }
1768                        wt++;
1769                    }
1770                }
1771            }
1772        }
1773        masterMap = cvMaps.getMasterMapForCommID();
1774        //(5-Band number)*0.25+(5-choice number)*0.25+(1-number of alternatives in the band)*0.25+distance from the next route choice*0.25
1775        if(b1>0 && B1!=null && B1.indexOf(preferredPathID)>-1)
1776        {
1777            choiceNum=1;
1778            val = (5-1)*0.25+(5-choiceNum)*0.25+(1-(b1-1))*0.25;
1779
1780            //Distance from next best alternative
1781            if(b2>0)
1782                val = val+1*0.25;
1783            else if (b3>0)
1784                val = val+(2)*0.25;
1785            else if (b4>0)
1786                val = val+(3)*0.25;
1787            else if (b5>0)
1788                val = val+(4)*0.25;
1789            else if (b2+b3+b4+b5==0)
1790                val = val+(5)*0.25;
1791
1792        pUIndex.setB1Val(String.valueOf(val));
1793
1794        //updating master map
1795                TreeMap subMap = masterMap.get(preferredPathID);
1796                if(subMap==null){
1797                    subMap = new TreeMap();
1798                }else if(subMap!=null && vehicleID!=null){
1799                    if(subMap.get(vehicleID)!=null){
1800                    val = Double.parseDouble(subMap.get(vehicleID).toString());
1801                    }
1802                }
1803                    subMap.put(vehicleID, val);
1804                    masterMap.put(preferredPathID, subMap);
1805        }
1806
1807        if(b2>0 && B2!=null && B2.indexOf(preferredPathID)>-1)
1808        {
1809            choiceNum=2;
1810            val = (5-2)*0.25+(5-choiceNum)*0.25+(1-(b2-1))*0.25;
1811
1812
1813            //Distance from next best alternative
1814            if (b3>0)
1815                val = val+(1)*0.25;
1816            else if (b4>0)
1817                val = val+(2)*0.25;
1818            else if (b5>0)
1819                val = val+(3)*0.25;
1820            else if (b1+b3+b4+b5==0)
1821                val = val+(5)*0.25;
1822
1823
1824        pUIndex.setB2Val(String.valueOf(val));
1825
1826        //updating master map
1827                TreeMap subMap = masterMap.get(preferredPathID);
1828                if(subMap==null){
1829                    subMap = new TreeMap();
1830                }else if(subMap!=null && vehicleID!=null){
1831                    if(subMap.get(vehicleID)!=null){
1832                    val = Double.parseDouble(subMap.get(vehicleID).toString());
1833                    }
1834                }
1835                subMap.put(vehicleID, val);
1836                masterMap.put(preferredPathID, subMap);
1837        }
1838
1839        if(b3>0  && B3!=null && B3.indexOf(preferredPathID)>-1)
1840        {
1841            choiceNum=3;
1842            val = (5-3)*0.25+(5-choiceNum)*0.25+(1-(b3-1))*0.25;
1843
1844
1845            //Distance from next best alternative
1846            if (b4>0)
1847                val = val+(1)*0.25;
1848            else if (b5>0)
1849                val = val+(2)*0.25;
1850            else if (b1+b2+b4+b5==0)
1851                val = val+(5)*0.25;
1852        pUIndex.setB3Val(String.valueOf(val));
1853
1854
1855        //updating master map
1856                TreeMap subMap = masterMap.get(preferredPathID);
1857                if(subMap==null){
1858                    subMap = new TreeMap();
1859                }else if(subMap!=null && vehicleID!=null){
1860                    if(subMap.get(vehicleID)!=null){
1861                    val = Double.parseDouble(subMap.get(vehicleID).toString());
1862                    }
1863                }
1864                subMap.put(vehicleID, val);
1865                masterMap.put(preferredPathID, subMap);
1866        }
1867
1868        if(b4>0 && B4!=null && B4.indexOf(preferredPathID)>-1)
1869        {
1870            choiceNum=4;
1871            val = (5-4)*0.25+(5-choiceNum)*0.25+(1-(b4-1))*0.25;
1872
1873
1874            //Distance from next best alternative
1875            if (b5>0)
1876                val = val+(1)*0.25;
1877            else if (b1+b2+b3+b5==0)
1878                val = val+(5)*0.25;
1879        pUIndex.setB4Val(String.valueOf(val));
1880
1881        //updating master map
1882                TreeMap subMap = masterMap.get(preferredPathID);
1883                if(subMap==null){
1884                    subMap = new TreeMap();
1885                }else if(subMap!=null && vehicleID!=null){
1886                    if(subMap.get(vehicleID)!=null){
1887                    val = Double.parseDouble(subMap.get(vehicleID).toString());
1888                    }
1889                }
1890                subMap.put(vehicleID, val);
1891                masterMap.put(preferredPathID, subMap);
1892        }
1893
1894        if(b5>0 && B5!=null && B5.indexOf(preferredPathID)>-1)
1895        {
1896
1897            choiceNum=5;
1898            val = (5-5)*0.25+(5-choiceNum)*0.25+(1-(b5-1))*0.25;
1899            if (b1+b2+b3+b4==0)
1900                val = val+(5)*0.25;
1901
1902        pUIndex.setB5Val(String.valueOf(val));
1903
1904        //updating master map
1905        cvMaps.getMasterMapForCommID();
1906                TreeMap subMap = masterMap.get(preferredPathID);
1907                if(subMap==null){
1908                    subMap = new TreeMap();
1909                }else if(subMap!=null && vehicleID!=null){
1910                    if(subMap.get(vehicleID)!=null){
1911                    val = Double.parseDouble(subMap.get(vehicleID).toString());
1912                    }
1913                }
1914                subMap.put(vehicleID, val);
1915                masterMap.put(preferredPathID, subMap);
1916        }
1917            } //while iter hasNext
1918
1919
1920
1921        }
1922        cvMaps.setPathID(segmentOnPath);
1923        cvMaps.setMasterMapForCommID(masterMap);
1924        cvMaps.setRouteRankMapForCommID(routeRankMap);
1925        QueueManager.setCVMaps(pUIndex.getCommID(), cvMaps);
1926
1927
1928
1929}//prefMult!=0
1930else if(preferenceMultiplier==0 && costMultiplier!=0){
1931//  System.out.println("as pref mult is zero ");
1932    String rtList = "";
1933    int listSize=0;
1934    TreeMap subMap = new TreeMap();
1935    ArrayList paths = getRoutesMatchingPath(segmentOnPath,yCoord);
1936    if(paths!=null){
1937        Iterator iter = paths.iterator();
1938        if(iter!=null){
1939            int wt = 1;
1940            masterMap = cvMaps.getMasterMapForCommID();
1941            while(iter.hasNext()){
1942                String rt = (String) iter.next();
1943                listSize++;
1944                
1945                routeRankMap.put(rt, wt);
1946                if(rtList!=null){
1947                    rtList=rtList.concat(rt);
1948
1949                    if(listSize<paths.size()){
1950                        rtList=rtList.concat(",");
1951                    }
1952                }
1953                wt++;
1954
1955                subMap = masterMap.get(rt);
1956                if(subMap==null){
1957                    subMap = new TreeMap();
1958                }
1959            subMap.put(vehicleID,5.0);
1960            masterMap.put(rt, subMap);
1961            }
1962        }
1963    }
1964
1965
1966            cvMaps.setPathID(segmentOnPath);
1967            cvMaps.setMasterMapForCommID(masterMap);
1968            cvMaps.setRouteRankMapForCommID(routeRankMap);
1969            QueueManager.setCVMaps(pUIndex.getCommID(), cvMaps);
1970
1971
1972
1973            pUIndex.setB1(rtList);
1974
1975            //pUIndex.setB1("41,42,43,44");
1976
1977
1978            pUIndex.setB1Val("0.7");
1979
1980
1981
1982}
1983    } catch (SQLException e) {
1984        // TODO Auto-generated catch block
1985        e.printStackTrace();
1986    }
1987
1988    return pUIndex;
1989}
1990
1991/**
1992 * This method is used to retrieve path IDs based on segment
1993 * @param segOnPath - segment 
1994 * @param yCoordinates - y coordinates
1995 * @return array list of the routes containing the given path
1996 */
1997private static ArrayList getRoutesMatchingPath(String segOnPath,String yCoordinates) {
1998
1999    String getRoutesInOrder = "select pathID from route where path like '%"+ segOnPath+ "%'" +" order by TT";
2000    ArrayList thesePaths = new ArrayList();
2001    ResultSet rsSelectAltPath = null;
2002    String vehPath = null;
2003    int rdCap = 0;
2004    try
2005    {
2006    
2007    if(segOnPath!=null && segOnPath.equals("s1")){
2008        thesePaths = new ArrayList();
2009        thesePaths.add("1");
2010        thesePaths.add("2");
2011        //thesePaths.add("19");
2012    }if(segOnPath!=null && segOnPath.equals("s2")){
2013        thesePaths = new ArrayList();
2014        thesePaths.add("3");
2015        thesePaths.add("4");
2016    /*  thesePaths.add("21");
2017        thesePaths.add("22");
2018        thesePaths.add("23");*/
2019
2020    }if(segOnPath!=null && segOnPath.equals("s24")){
2021        thesePaths = new ArrayList();
2022        thesePaths.add("5");
2023        thesePaths.add("6");
2024
2025    }if(segOnPath!=null && segOnPath.equals("s37")){
2026        thesePaths = new ArrayList();
2027        thesePaths.add("7");
2028        thesePaths.add("8");
2029
2030    }if(segOnPath!=null && segOnPath.equals("s39")){
2031        thesePaths = new ArrayList();
2032        thesePaths.add("9");
2033        thesePaths.add("10");
2034
2035    }if(segOnPath!=null && segOnPath.equals("s43")){
2036        thesePaths = new ArrayList();
2037        thesePaths.add("11");
2038        thesePaths.add("12");
2039
2040    }if(segOnPath!=null && segOnPath.equals("s27")){
2041        thesePaths = new ArrayList();
2042        thesePaths.add("13");
2043        thesePaths.add("14");
2044
2045    }if(segOnPath!=null && segOnPath.equals("s10")){
2046        thesePaths = new ArrayList();
2047        thesePaths.add("15");
2048        thesePaths.add("16");
2049
2050    }if(segOnPath!=null && segOnPath.equals("s17")){
2051        thesePaths = new ArrayList();
2052        thesePaths.add("17");
2053        thesePaths.add("18");
2054
2055    }if(segOnPath!=null && segOnPath.equals("s31")){
2056        thesePaths = new ArrayList();
2057        thesePaths.add("24");
2058        thesePaths.add("25");
2059
2060    }if(segOnPath!=null && segOnPath.equals("s11")){
2061        thesePaths = new ArrayList();
2062        thesePaths.add("26");
2063        thesePaths.add("27");
2064
2065    }
2066
2067    } catch (Exception e) {
2068        e.printStackTrace();
2069    }
2070    return thesePaths;
2071    // TODO Auto-generated method stub
2072
2073}
2074public static synchronized PreferenceUtilityIndex getPreferenceUtilityIndex(String vehicleID,String commStr, double preferenceMultiplier, double costMultiplier,String segmentOnPath,String yCoord,CommunicatingVehicles cv)
2075{
2076    PreferenceUtilityIndex preferenceUtilityIndex = new PreferenceUtilityIndex(vehicleID,commStr);
2077
2078    classifyIntoBands(vehicleID, preferenceUtilityIndex,preferenceMultiplier,costMultiplier,segmentOnPath,yCoord,cv);
2079
2080    return preferenceUtilityIndex;
2081}
2082
2083public static void setRegisteredVehicleInfo(ConcurrentHashMap<String, PreferenceUtilityIndex> regVInfo)
2084{
2085    registeredVehicleInfo = regVInfo;
2086}
2087
2088/**
2089 * This method is used to rank the routes based on the preference utility index
2090 * @param pIndex - preference utility index
2091 * @param communicID - communication ID
2092 * @return map of routes assigned to agents
2093 */
2094public static synchronized ConcurrentHashMap rankTheRoutesAndAssignAgents(PreferenceUtilityIndex pIndex,String communicID)
2095{
2096    CommunicatingVehicles commVehicles = QueueManager.getCVMaps(communicID);
2097    if(commVehicles==null){
2098        
2099        commVehicles = QueueManager.getCVMaps(communicID);
2100    }else{
2101    masterMap = commVehicles.getMasterMapForCommID();
2102    routeRankMap= commVehicles.getRouteRankMapForCommID();
2103    masterMapCpy = new ConcurrentHashMap<String, TreeMap>(masterMap);
2104    ValueComparator bvcRouteRank =  new ValueComparator(routeRankMap);
2105    TreeMap sortedRouteRankMap = new TreeMap(bvcRouteRank);
2106    sortedRouteRankMap.putAll(routeRankMap);
2107    Set<Entry<String, Double>> entries = sortedRouteRankMap.entrySet();
2108    ConcurrentHashMap routAssgnMap = new ConcurrentHashMap();
2109    TreeMap subMap = new TreeMap();
2110    TreeMap subMapCpy = null;
2111    int cap = 0, k =0,cnt=0,subEntriesSize=0,oneCap=0,otherCap=0,thirdCap=0;
2112    String routeCapacity=null;
2113    boolean unassigned = true;
2114    String routeAssign = "";
2115    String assignAltRouteVhicles="";
2116    ArrayList assignAltRouteVhiclesLst= new ArrayList();
2117    ArrayList newAssignAltRouteVhicles= new ArrayList();
2118    String fullCapRoads = "";
2119    //Print the Route Choice Map
2120    //System.out.println("****Final Route Rank Map******");
2121    Set routeRankSet = routeRankMap.entrySet();
2122    Iterator secIter = routeRankSet.iterator();
2123
2124    int[] x= new int[10];
2125    int cntRatio=0;
2126    Map sortedRouteMapForRatio =  sortByComparator(routeRankMap);
2127    entries = sortedRouteMapForRatio.entrySet();
2128    try{
2129    if(entries!=null && !entries.isEmpty()){
2130        for(Iterator it = entries.iterator(); it.hasNext();) {
2131            Map.Entry entry = (Entry) it.next();
2132            String route =  (String) entry.getKey();
2133            int num = (int) entry.getValue();
2134            x[cntRatio]=num;
2135            cntRatio++;
2136
2137        }
2138    }
2139    }catch(Exception e){
2140        e.printStackTrace();
2141    }
2142
2143
2144
2145    String vIDsAssignedToRoutes ="";
2146    Map sortedRouteMap =  sortByComparator(routeRankMap);
2147    entries = sortedRouteMap.entrySet();
2148    int iterRtCnt=0;
2149    if(entries!=null && !entries.isEmpty()){
2150        for(Iterator it = entries.iterator(); it.hasNext();) {
2151
2152            k=0;
2153            unassigned = true;
2154            Map.Entry entry = (Entry) it.next();
2155            String route =  (String) entry.getKey();
2156            subMap = masterMapCpy.get(route);
2157            if(subMap!=null){
2158
2159            Map<String,Double> sortedsubMap =  sortByComparator(subMap);
2160            Set<Entry<String, Double>> subEntries = sortedsubMap.entrySet();
2161
2162
2163            if(subEntries!=null && !subEntries.isEmpty()){
2164
2165
2166                if(subMap.size()== 20){
2167                    System.out.println("vehicle seed");
2168                }
2169                subEntriesSize = subEntries.size();
2170                if(subEntries.size()>7){
2171
2172                    if(subEntries.size()<=30 && subEntries.size()>20){
2173                        oneCap = subEntriesSize-14;
2174                        otherCap = subEntriesSize-oneCap;
2175                    }else if(subEntries.size()<=35 && subEntries.size()>30){
2176                        oneCap = subEntriesSize-14;
2177                        otherCap = subEntriesSize-oneCap;
2178                    }else if(subEntries.size()<=40 && subEntries.size()>35){
2179                        oneCap = subEntriesSize-14;
2180                        otherCap = subEntriesSize-oneCap;
2181                    }else if(subEntries.size()<=20 && subEntries.size()>14){
2182                        oneCap = subEntriesSize-10;
2183                        otherCap = subEntriesSize-oneCap;
2184                    }else if(subEntries.size()<=14){
2185                        oneCap = subEntriesSize-7;
2186                        otherCap = subEntriesSize-oneCap;
2187                    }else if(subEntries.size()<=45 && subEntries.size()>40){
2188                        oneCap = subEntriesSize-16;
2189                        otherCap = subEntriesSize-oneCap;
2190                    }
2191                }else{
2192                    oneCap = 0;
2193                    otherCap = subEntriesSize;
2194                }
2195
2196
2197
2198
2199
2200            /*  //disproportion
2201            if(subEntries.size()>7){
2202                    if(subEntries.size()<=20){
2203                        oneCap = subEntriesSize-7;
2204                        otherCap = subEntriesSize-oneCap;
2205                    }else if(subEntries.size()<=30){
2206                        oneCap = subEntriesSize-10;
2207                        otherCap = subEntriesSize-oneCap;
2208                    }else{
2209                        oneCap = subEntriesSize-18;
2210                        otherCap = subEntriesSize-oneCap;
2211                    }
2212                }else{
2213                    oneCap = subEntriesSize;
2214                    otherCap = 0;
2215                }
2216                */
2217            
2218            //congested route
2219                /*//scenario 1
2220                if(route!=null && (route.equals("21") ||route.equals("22") || route.equals("23"))){
2221                    oneCap = 8;
2222                    otherCap = 6;
2223
2224                }*//*
2225                if(route!=null && (route.equals("5")||route.equals("6") ||route.equals("7")||route.equals("8")||route.equals("9") ||route.equals("10")||route.equals("17")||route.equals("18")||route.equals("21")||route.equals("22")||route.equals("23")||route.equals("24")||route.equals("25"))){
2226                    oneCap = subEntriesSize;
2227                    otherCap = 0;
2228                }
2229                if(route!=null && (route.equals("6") ||route.equals("8") ||route.equals("10")||route.equals("17")||route.equals("21")||route.equals("22")||route.equals("25"))){
2230
2231                        if(oneCap<otherCap){
2232                            cap = oneCap;
2233                        }else{
2234                            cap = otherCap;
2235                        }
2236
2237                    //iterRtCnt++;
2238                }else{
2239
2240                    if(route.equals("21")){
2241                        cap = 6;//oneCap/2;
2242                    }else if (route.equals("22")){
2243                        cap = 6;//oneCap-oneCap/2;
2244                    }else if (route.equals("23")){
2245                        cap = 8;//oneCap-oneCap/2;
2246                    }
2247                    else if(oneCap>otherCap){
2248                        cap = oneCap;
2249                    }else{
2250                        cap = otherCap;
2251                    }
2252                }*/
2253
2254                //scenario 1 end
2255                //scenario 2
2256
2257            //final - congested scenario c!=0
2258            /*
2259                if(route!=null && (route.equals("21") ||route.equals("22") || route.equals("23"))){
2260                    oneCap = 18;
2261                    otherCap = 7;
2262
2263                }
2264
2265            if(route!=null && (route.equals("3")||route.equals("4") ||route.equals("5")||route.equals("6") ||route.equals("11") ||route.equals("12")||route.equals("13") ||route.equals("14")||route.equals("17")||route.equals("18")||route.equals("24")||route.equals("25"))){
2266                oneCap = subEntriesSize;
2267                otherCap = 0;
2268            }
2269            if(route!=null && (route.equals("1") ||route.equals("4") ||route.equals("6") || route.equals("8") || route.equals("10") || route.equals("11") || route.equals("13")  || route.equals("14") || route.equals("16")|| route.equals("17")|| route.equals("21")|| route.equals("25")|| route.equals("27"))){
2270                    if(oneCap>otherCap){
2271                        cap = otherCap;
2272                    }else{
2273                        cap=oneCap;
2274                    }
2275                    if(route.equals("21")){
2276                        cap=0;
2277                    }
2278            }else{
2279                    if(oneCap>otherCap){
2280                        cap = oneCap;
2281                    }else{
2282                        cap=otherCap;
2283                    }
2284            }*/
2285            //final - congested scenario c!=0
2286
2287            //pref!=0
2288
2289                
2290/*              if(route!=null && (route.equals("21") ||route.equals("22") || route.equals("23"))){
2291                    oneCap = 10;
2292                    otherCap = 5;
2293
2294                }
2295
2296
2297                if(route!=null && (route.equals("1") || route.equals("3") || route.equals("5") || route.equals("7") || route.equals("10") || route.equals("12") || route.equals("14") || route.equals("16")|| route.equals("18")|| route.equals("22")|| route.equals("23")|| route.equals("27"))){
2298                        if(oneCap>otherCap){
2299                            cap = otherCap;
2300                        }else{
2301                            cap=oneCap;
2302                        }
2303                        //iterRtCnt++;
2304                    }else{
2305                        if(oneCap>otherCap){
2306                            cap = oneCap;
2307                        }else{
2308                            cap=otherCap;
2309                        }
2310                    }
2311                
2312*/
2313
2314
2315
2316
2317            //congested route
2318
2319                //cost!=0
2320                // shortest time - 1,4,5/6,7,9/10,11,13,15,17
2321
2322                if(route!=null && (route.equals("24") ||route.equals("26") ||route.equals("21") || route.equals("2") || route.equals("3") || route.equals("5") || route.equals("8") || route.equals("10") || route.equals("12") || route.equals("14") || route.equals("16")|| route.equals("18"))){
2323                    if(oneCap>otherCap){
2324                        cap = otherCap;
2325                    }else{
2326                        cap=oneCap;
2327                    }
2328                    //iterRtCnt++;
2329                }else{
2330                    if(oneCap>otherCap){
2331                        cap = oneCap;
2332                    }else{
2333                        cap=otherCap;
2334                    }
2335                }
2336
2337                
2338                //2,4,6,8,10,11,13,15,17 are familiar
2339                //pref!=0
2340
2341            /*  if(route!=null && (route.equals("1") || route.equals("3") || route.equals("6") || route.equals("7") || route.equals("10") || route.equals("12") || route.equals("14") || route.equals("16")|| route.equals("18"))){
2342                    if(oneCap>otherCap){
2343                        cap = otherCap;
2344                    }else{
2345                        cap=oneCap;
2346                    }
2347                    //iterRtCnt++;
2348                }else{
2349                    if(oneCap>otherCap){
2350                        cap = oneCap;
2351                    }else{
2352                        cap=otherCap;
2353                    }
2354                }   
2355*/
2356                
2357                
2358                
2359                
2360                //scenario 2 end
2361
2362
2363                for(Iterator iter = subEntries.iterator(); iter.hasNext();) {
2364
2365                    String vID = "";
2366                    unassigned = true;
2367                    Map.Entry subEntry = (Entry) iter.next();
2368                    vID =  (String) subEntry.getKey();
2369
2370
2371
2372                    if(k<cap){
2373
2374                    if(vIDsAssignedToRoutes!=null && vIDsAssignedToRoutes.length()>0){
2375                        if(stringAbsent(vIDsAssignedToRoutes,vID)){
2376                        vIDsAssignedToRoutes=vIDsAssignedToRoutes+","+vID;
2377                        if(assignAltRouteVhicles!=null && assignAltRouteVhicles.length()>0){
2378                            if(assignAltRouteVhicles.indexOf(vID)>-1){
2379                                assignAltRouteVhiclesLst.remove(vID);
2380                            }
2381                        }
2382                        }   else{
2383                            unassigned = false;
2384                            continue;
2385                        }
2386                    }else{
2387                        vIDsAssignedToRoutes=vID;
2388                        if(assignAltRouteVhicles!=null && assignAltRouteVhicles.length()>0){
2389                            if(assignAltRouteVhicles.indexOf(vID)>-1){
2390                                assignAltRouteVhiclesLst.remove(vID);
2391                            }
2392                        }
2393                    }
2394                    if(unassigned){
2395                        routAssgnMap.put(vID, route);
2396                        if(vID!=null && vID.equals("#5")){
2397
2398                                //System.out.println("route for #5 is : "+route);
2399
2400                        }
2401                        cnt++;
2402                    }
2403                    unassigned = false;
2404            //      System.out.println("ROUTEASSGNMAP ROUTEASSGNMAP "+vID+"AND ROUTE "+route);
2405                    //masterMapCpy.put(route,subMap);
2406                    k++;
2407                    }else{
2408                        unassigned=true;
2409                        if(assignAltRouteVhicles!=null && assignAltRouteVhicles.length()>0){
2410                            if(assignAltRouteVhicles.indexOf(vID)<=-1 && vIDsAssignedToRoutes.indexOf(vID)<=-1){
2411                                assignAltRouteVhicles=assignAltRouteVhicles+","+vID;
2412                                assignAltRouteVhiclesLst.add(vID);
2413                            }   else{
2414                                continue;
2415                            }
2416                        }else{
2417                            assignAltRouteVhicles=vID;
2418                            assignAltRouteVhiclesLst.add(vID);
2419                        }
2420                        if(fullCapRoads!=null && fullCapRoads.length()>0){
2421                            if(fullCapRoads.indexOf(route)<=-1){
2422                                fullCapRoads=fullCapRoads+","+route;
2423
2424                            }   else{
2425                                continue;
2426                            }
2427                        }else{
2428                            fullCapRoads=route;
2429                        }
2430                    }
2431                }
2432
2433
2434            }
2435
2436
2437        }
2438
2439    }
2440        Iterator iter = assignAltRouteVhiclesLst.iterator();
2441
2442
2443        if(iter!=null){
2444            while(iter.hasNext()){
2445                String vID = (String) iter.next();
2446                if(vIDsAssignedToRoutes!=null && vIDsAssignedToRoutes.indexOf(vID)<=-1){
2447                    routeAssign = assignAlternateRoute(vID,fullCapRoads);
2448                    if(routeAssign!=null){
2449                    routAssgnMap.put(vID, routeAssign);
2450                    cnt++;
2451                    }
2452                }
2453
2454            }
2455        }
2456    }
2457
2458        if(routAssgnMap!=null && (routAssgnMap.size()==40 || routAssgnMap.size()==30 || routAssgnMap.size()==25 || routAssgnMap.size()==20 || routAssgnMap.size()==35 || routAssgnMap.size()==15)){
2459        System.out.println("Printing initial assignments");
2460        Set initRouteRankSet = routAssgnMap.entrySet();
2461        Iterator initSec = initRouteRankSet.iterator();
2462
2463        int lenSellerAgents=0;
2464
2465
2466
2467
2468        Set routeRankSetOther = routeRankMap.entrySet();
2469        Iterator secIterOther = routeRankSetOther.iterator();
2470        while(initSec!=null && initSec.hasNext()){
2471            Map.Entry subEntry = (Entry)initSec.next();
2472            String key = (String) subEntry.getKey();
2473            String val = (String) subEntry.getValue();
2474        System.out.println("Initially : "+key + " and val: "+val);
2475        }
2476        }
2477
2478    return routAssgnMap;
2479    }
2480    return null;
2481
2482}
2483
2484
2485private static boolean stringAbsent(String toSearch, String s) {
2486    String fragStr = null;
2487    if(toSearch!=null && s!=null){
2488        StringTokenizer st = new StringTokenizer(toSearch,",");
2489        while(st!=null && st.hasMoreTokens()){
2490            fragStr = st.nextToken();
2491            if(fragStr!=null && fragStr.equals(s)){
2492                return false;
2493            }
2494        }
2495    }
2496
2497    return true;
2498}
2499
2500
2501/**
2502 * This method assigns alternate route
2503 * @param vID vehicle ID
2504 * @param fullCapacityRoads route
2505 * @return route ID 
2506 */
2507
2508private static String assignAlternateRoute(String vID, String fullCapacityRoads) {
2509    ArrayList<String> altRoutesTT = getAlternatePathsOrderByTT(vID, null, null, false);
2510    String tempRoute="";
2511    Iterator iter = altRoutesTT.iterator();
2512    while(iter!=null && iter.hasNext()){
2513        String route = (String) iter.next();
2514
2515        if(route.equals("s1,s2,s4,s5,s6,s52,s7,s8,s9,s10,s11,s32,s17,s18,s19,s22")){
2516            tempRoute="1";}
2517        else if(route.equals("s1,s45,s3,s37,s46,s50,s51,s42,s27,s30,s31,s32,s17,s18,s19,s22"))
2518            tempRoute="2";
2519        else if(route.equals("s2,s23,s24,s25,s26,s27,s30,s31,s32,s17,s18,s19,s22"))
2520            tempRoute="3";
2521        else if(route.equals("s2,s4,s5,s6,s52,s7,s8,s9,s10,s11,s32,s17,s18,s19,s22"))
2522            tempRoute="4";
2523        else if(route.equals("s24,s53,s52,s7,s8,s9,s10,s12,s13,s17,s18,s19,s22"))
2524            tempRoute="5";
2525        else if(route.equals("s24,s25,s26,s27,s30,s31,s32,s17,s18,s19,s22"))
2526            tempRoute="6";
2527        else if(route.equals("s37,s38,s39,s40,s43,s54,s55,s17,s18,s19,s22"))
2528            tempRoute="7";
2529        else if(route.equals("s37,s46,s50,s51,s42,s27,s30,s31,s32,s17,s18,s19,s22"))
2530            tempRoute="8";
2531        else if(route.equals("s40,s43,s54,s55,s17,s18,s19,s22"))
2532            tempRoute="9";
2533        else if(route.equals("s40,s41,s42,s27,s30,s31,s32,s17,s18,s19,s22"))
2534            tempRoute="10";
2535        else if(route.equals("s43,s44,s30,s31,s32,s17,s18,s19,s22"))
2536            tempRoute="11";
2537        else if(route.equals("s43,s54,s55,s17,s18,s19,s22"))
2538            tempRoute="12";
2539        else if(route.equals("s27,s30,s31,s32,s17,s18,s19,s22"))
2540            tempRoute="13";
2541        else if(route.equals("s27,s28,s29,s8,s9,s10,s12,s13,s17,s18,s19,s22"))
2542            tempRoute="14";
2543        else if(route.equals("s10,s12,s13,s17,s18,s19,s22"))
2544            tempRoute="15";
2545        else if(route.equals("s10,s14,s15,s16,s13,s17,s18,s19,s22"))
2546            tempRoute="16";
2547        else if(route.equals("s17,s18,s19,s22"))
2548            tempRoute="17";
2549        else if(route.equals("s17,s18,s20,s21,s22"))
2550            tempRoute="18";
2551        else if(route.equals("s2,s4,s5,s6,s52,s7,s8,s9,s10,s12,s13,s17,s18,s19,s22"))
2552            tempRoute="21";
2553        else if(route.equals("s2,s23,s24,s25,s26,s27,s30,s31,s32,s17,s18,s19,s22"))
2554            tempRoute="22";
2555        else if(route.equals("s2,s47,s48,s58,s57,s40,s43,s54,s55,s17,s18,s19,s22"))
2556            tempRoute="23";
2557        else if(route.equals("s31,s11,s12,s13,s17,s18,s19,s22"))
2558            tempRoute="24";
2559        else if(route.equals("s31,s32,s17,s18,s19,s22"))
2560            tempRoute="25";
2561        else if(route.equals("s11,s12,s13,s17,s18,s19,s22"))
2562            tempRoute="26";
2563        else if(route.equals("s11,s14,s15,s16,s17,s18,s19,s22"))
2564            tempRoute="27";
2565        if(route!=null && fullCapacityRoads.indexOf(tempRoute)<=-1){
2566            return tempRoute;
2567        }
2568    }
2569    return null;
2570
2571
2572}
2573
2574
2575/**
2576 * This method retrieves the road segment parameters of the route choices
2577 * @param routeChoices map of route choices and vehicles
2578 * @return list of road segments parameters
2579 */
2580public static synchronized ArrayList<RoadSegment> selectRoadSegmentParams(ConcurrentHashMap routeChoices){
2581
2582    ArrayList<RoadSegment> roadSegmentList = new ArrayList<RoadSegment>();
2583    boolean checkSeg = false;
2584    if(routeChoices==null){
2585        System.out.println("rt ch null");
2586    }else{
2587    ConcurrentHashMap otherTempHashMap = new ConcurrentHashMap(routeChoices);
2588    ConcurrentHashMap tempHashMap = new ConcurrentHashMap();
2589    RoadSegment roadSeg = new RoadSegment();
2590    String segmentList = "";
2591    String vID = "";
2592    String getSegmentData = "select segmentID,length, freeflowspeed,capacity,thresholdCap from roadsegment where segmentID in (";
2593    double indx = 0.0;
2594    String path,segID;
2595    double length;
2596    int cnt = 0;
2597    int capacity=0,tCapacity=0;
2598    float freeFlowSpeed=0.0f;
2599    if(routeChoices!=null && routeChoices.size()>0){
2600    try {
2601
2602        tempHashMap = getSegmentCount(routeChoices);
2603
2604        PreparedStatement st = null;
2605        Set routeSet = otherTempHashMap.entrySet();
2606
2607        if(routeSet!=null && !routeSet.isEmpty()){
2608            for(Iterator it = routeSet.iterator(); it.hasNext();) {
2609                Map.Entry subEntry = (Entry) it.next();
2610                vID =  (String) subEntry.getKey();
2611                String pathID = (String) subEntry.getValue();
2612
2613                Object obj=null;
2614
2615                path = (String) pathIDTopath.get(pathID);
2616                if(path!=null){
2617
2618
2619
2620                StringTokenizer stt = new StringTokenizer(path,",");
2621                while(stt!=null &&stt.hasMoreTokens()){
2622
2623                String seg = stt.nextToken();
2624                if(segmentList.length()>0 || segmentList.indexOf(seg)<-1){
2625                    segmentList=segmentList+",'"+seg+"'";
2626                }else{
2627                    segmentList="'"+seg+"'";
2628                }
2629                }
2630            }
2631
2632
2633            }
2634        }
2635
2636    //  System.out.println("malformed segment list "+segmentList+"for vehicle with ID "+vID);
2637        segmentList = checkIfSegmentPresentInList(roadSegmentList,segmentList);
2638        getSegmentData= getSegmentData+segmentList+")";
2639        st =  QueueManager.getConnection().prepareStatement(getSegmentData);
2640        ResultSet rs = st.executeQuery();
2641        if(rs!=null){
2642            while(rs.next())
2643            {
2644                segID = rs.getString(1);
2645
2646                length = rs.getInt(2);
2647                freeFlowSpeed = getFreeFlowSpeed(segID);
2648                capacity = rs.getInt(4);
2649                tCapacity = rs.getInt(5);
2650                Object objCnt =  tempHashMap.get(segID);
2651                roadSeg = new RoadSegment();
2652
2653                roadSeg.setSegmentID(segID);
2654                roadSeg.setSegmentLength(length);
2655
2656
2657                roadSeg.setSegmentFreeFlowSpeed(freeFlowSpeed);
2658
2659                roadSeg.setSegmentCapacity(capacity);
2660                if(objCnt!=null){
2661                    cnt = Integer.parseInt(objCnt.toString());
2662                }else{
2663                    cnt=0;
2664                }
2665                roadSeg.setOccupiedCapacity(cnt);
2666                roadSeg.setThresholdCapacity(tCapacity);
2667
2668                roadSegmentList.add(roadSeg);
2669
2670            }
2671        }
2672
2673
2674    } catch (SQLException e) {
2675        // TODO Auto-generated catch block
2676        e.printStackTrace();
2677    }
2678    }
2679    }
2680    return roadSegmentList;
2681}
2682
2683
2684private static float getFreeFlowSpeed(String segID) {
2685        if(segID!=null){
2686            if(segID.equals("s25") || segID.equals("s26") || segID.equals("s39")|| segID.equals("s40")|| segID.equals("s45")|| segID.equals("s46")|| segID.equals("s49")|| segID.equals("s50")|| segID.equals("s51")){
2687                                    return 0.0011f;
2688
2689            }else if(segID.equals("s11") || segID.equals("s14") || segID.equals("s23")|| segID.equals("s24")|| segID.equals("s27")|| segID.equals("s30") || segID.equals("s37") || segID.equals("s38")|| segID.equals("s56")|| segID.equals("s57")){
2690
2691
2692                    return 0.0013f*1000;
2693
2694            }else if(segID.equals("s1") || segID.equals("s2") || segID.equals("s3")|| segID.equals("s4")|| segID.equals("s5")|| segID.equals("s9") ||
2695                    segID.equals("s10") || segID.equals("s12")|| segID.equals("s15")|| segID.equals("s20")|| segID.equals("s21")|| segID.equals("s22")|| segID.equals("s28") ||
2696                segID.equals("s29") || segID.equals("s31")|| segID.equals("s36")|| segID.equals("s41")|| segID.equals("s42")|| segID.equals("s43")|| segID.equals("s44")||
2697                segID.equals("s47")|| segID.equals("s48")|| segID.equals("s53")|| segID.equals("s54")|| segID.equals("s58")){
2698
2699                    return 0.0016f*1000;
2700
2701            //  System.out.println("speed for n: "+speed+ " and n "+n+ "segment "+segID);
2702            }else if(segID.equals("s6") || segID.equals("s7")||segID.equals("s8")|| segID.equals("s13")|| segID.equals("s16")|| segID.equals("s17") ||
2703                    segID.equals("s18") || segID.equals("s19")|| segID.equals("s32")|| segID.equals("s33") || segID.equals("s34") || segID.equals("s35")|| segID.equals("s52")|| segID.equals("s55")){
2704
2705                    return 0.0019f*1000;
2706            }
2707        }
2708        return 0.1f;
2709}
2710
2711private static String checkIfSegmentPresentInList(ArrayList<RoadSegment> roadSegmentList, String segmentList) {
2712    StringTokenizer st = null;
2713    String segNotFound=null,token=null;
2714    boolean flagPresent=false;
2715    if(roadSegmentList!=null && segmentList!=null){
2716        Iterator listIter = roadSegmentList.iterator();
2717        st = new StringTokenizer(segmentList,",");
2718                while(st!=null && st.hasMoreTokens()){
2719                    token=st.nextToken();
2720                    while(listIter!=null && listIter.hasNext()){
2721                        RoadSegment roadSegm = (RoadSegment) listIter.next();
2722                        if(roadSegm!=null && segmentList!=null){
2723                            if(token!=null && roadSegm.getSegmentID()!=null){
2724                                if(token.equals(roadSegm.getSegmentID())){
2725                                    flagPresent = true;
2726                                    break;
2727                                }else{
2728                                    flagPresent=false;
2729                                }
2730                            }//token! null
2731                        }//roadSegm! null
2732                    } //listIter!=null
2733                    if(!flagPresent){
2734                        if(segNotFound==null){
2735                            segNotFound = new String (token);
2736                        }else{
2737                            if(segNotFound.indexOf(token)<=-1){
2738                                segNotFound+=","+token;
2739                            }else{
2740
2741                            }
2742                        }
2743                    }
2744                }//st! null
2745        }
2746
2747
2748    return segNotFound;
2749}
2750
2751
2752
2753
2754public static synchronized ConcurrentHashMap getSegmentCount(ConcurrentHashMap routeChoices){
2755
2756    ArrayList<RoadSegment> roadSegmentList = new ArrayList<RoadSegment>();
2757    ConcurrentHashMap otherTempHashMap = new ConcurrentHashMap(routeChoices);
2758    ArrayList pathList = new ArrayList();
2759    ConcurrentHashMap tempHashMap = new ConcurrentHashMap();
2760    RoadSegment roadSeg = new RoadSegment();
2761    String segmentList = "";
2762    String vID = "";
2763    String getSegmentData = "select pathID,path from route where pathID in (";
2764    double indx = 0.0;
2765    String path,vPath;
2766    int pathID;
2767    double length;
2768    int cnt = 0;
2769    int freeFlowSpeed=0,capacity=0,tCapacity=0;
2770    Object obj = null;
2771    if(routeChoices!=null && routeChoices.size()>0){
2772    try {
2773        PreparedStatement st = null;
2774        Set routeSet = otherTempHashMap.entrySet();
2775
2776        if(routeSet!=null && !routeSet.isEmpty()){
2777            for(Iterator it = routeSet.iterator(); it.hasNext();) {
2778                Map.Entry subEntry = (Entry) it.next();
2779                vID =  (String) subEntry.getKey();
2780                vPath = (String) subEntry.getValue();
2781
2782
2783                if(vPath.equals("1")){
2784                    tempSegmentList="s1,s2,s4,s5,s6,s52,s7,s8,s9,s10,s11,s32,s17,s18,s19,s22";}
2785                else if(vPath.equals("2"))
2786                    tempSegmentList="s1,s45,s3,s37,s46,s50,s51,s42,s27,s30,s31,s32,s17,s18,s19,s22";
2787                else if(vPath.equals("3"))
2788                    tempSegmentList="s2,s23,s24,s25,s26,s27,s30,s31,s32,s17,s18,s19,s22";
2789                if(vPath.equals("4")){
2790                    tempSegmentList="s2,s4,s5,s6,s52,s7,s8,s9,s10,s11,s32,s17,s18,s19,s22";}
2791                if(vPath.equals("5")){
2792                    tempSegmentList="s24,s53,s52,s7,s8,s9,s10,s12,s13,s17,s18,s19,s22";}
2793                if(vPath.equals("6")){
2794                    tempSegmentList="s24,s25,s26,s27,s30,s31,s32,s17,s18,s19,s22";}
2795                if(vPath.equals("7")){
2796                    tempSegmentList="s37,s38,s39,s40,s43,s54,s55,s17,s18,s19,s22";}
2797                if(vPath.equals("8")){
2798                    tempSegmentList="s37,s46,s50,s51,s42,s27,s30,s31,s32,s17,s18,s19,s22";}
2799                if(vPath.equals("9")){
2800                    tempSegmentList="s40,s43,s54,s55,s17,s18,s19,s22";}
2801                if(vPath.equals("10")){
2802                    tempSegmentList="s40,s41,s42,s27,s30,s31,s32,s17,s18,s19,s22";}
2803                if(vPath.equals("11")){
2804                    tempSegmentList="s43,s44,s30,s31,s32,s17,s18,s19,s22";}
2805                if(vPath.equals("12")){
2806                    tempSegmentList="s43,s54,s55,s17,s18,s19,s22";}
2807                if(vPath.equals("13")){
2808                    tempSegmentList="s27,s30,s31,s32,s17,s18,s19,s22";}
2809                if(vPath.equals("14")){
2810                    tempSegmentList="s27,s28,s29,s8,s9,s10,s12,s13,s17,s18,s19,s22";}
2811                if(vPath.equals("15")){
2812                    tempSegmentList="s10,s12,s13,s17,s18,s19,s22";}
2813                if(vPath.equals("16")){
2814                    tempSegmentList="s10,s14,s15,s16,s13,s17,s18,s19,s22";}
2815                if(vPath.equals("17")){
2816                    tempSegmentList="s17,s18,s19,s22";}
2817                if(vPath.equals("18")){
2818                    tempSegmentList="s17,s18,s20,s21,s22";}
2819
2820                if(vPath.equals("21")){
2821                    tempSegmentList="s2,s4,s5,s6,s52,s7,s8,s9,s10,s12,s13,s17,s18,s19,s22";}
2822                if(vPath.equals("22")){
2823                    tempSegmentList="s2,s23,s24,s25,s26,s27,s30,s31,s32,s17,s18,s19,s22";}
2824                if(vPath.equals("23")){
2825                    tempSegmentList="s2,s47,s48,s58,s57,s40,s43,s54,s55,s17,s18,s19,s22";}
2826                if(vPath.equals("24")){
2827                    tempSegmentList="s31,s11,s12,s13,s17,s18,s19,s22";}
2828                if(vPath.equals("25")){
2829                    tempSegmentList="s31,s32,s17,s18,s19,s22";}
2830                if(vPath.equals("26")){
2831                    tempSegmentList="s11,s12,s13,s17,s18,s19,s22";}
2832                if(vPath.equals("27")){
2833                    tempSegmentList="s11,s14,s15,s16,s17,s18,s19,s22";}
2834
2835                pathIDTopath.put(vPath,tempSegmentList);
2836
2837
2838            }
2839
2840        }
2841
2842
2843            for(Iterator it = routeSet.iterator(); it.hasNext();) {
2844                Map.Entry subEntry = (Entry) it.next();
2845                vID =  (String) subEntry.getKey();
2846                vPath = (String) subEntry.getValue();
2847                String pth = (String) pathIDTopath.get(vPath);
2848                if(pth!=null){
2849                pathList.add(pth);
2850                }
2851
2852            }
2853
2854
2855
2856            if(pathList!=null){
2857            for(Iterator it = pathList.iterator(); it.hasNext();) {
2858
2859
2860                String route = (String) it.next();
2861
2862                if(route!=null){
2863                    StringTokenizer routeTokens = new StringTokenizer(route,",");
2864                    if(routeTokens!=null){
2865                        while(routeTokens.hasMoreElements()){
2866                            String rtSeg = routeTokens.nextToken();
2867                            if(route!=null){
2868                                obj =  tempHashMap.get(rtSeg);
2869                            if(obj!=null){
2870                                cnt = Integer.parseInt(obj.toString());
2871                            }else{
2872                                cnt=0;
2873                            }
2874                            if(cnt==0){
2875                                tempHashMap.put(rtSeg,1);
2876                            }else{
2877                                cnt++;
2878                                tempHashMap.put(rtSeg,cnt);
2879                            }
2880                        }
2881                        }
2882                    }
2883                }
2884            }
2885        }
2886    }catch(Exception e)
2887    {
2888        e.printStackTrace();
2889    }
2890
2891    }
2892    return tempHashMap;
2893
2894}
2895
2896public static String selectRandomRoute(ConcurrentHashMap routeChoice) {
2897    Random rand = new Random();
2898    Set routeSet = routeChoice.entrySet();
2899    Object o = routeSet.toArray()[rand.nextInt(routeSet.size())];
2900
2901    return o.toString();
2902}
2903
2904public static Map<String, Double> getRoutesInOrderForDROP(CommunicatingVehicles vehMaps){
2905    ConcurrentHashMap routeRankHashMap = vehMaps.getRouteRankMapForCommID();
2906    Map<String,Double> sortedsubMap =  sortByComparator(routeRankHashMap);
2907    return sortedsubMap;
2908}
2909
2910public static double evaluateDegreeOfUserSatisfaction(ConcurrentHashMap routeChoice,String vID)
2911{
2912    double degreeOfUserSatisfaction=0.0;
2913    if(routeChoice!=null){
2914        Set routeChoiceSet = routeChoice.entrySet();
2915        Iterator iter = routeChoiceSet.iterator();
2916        while(iter!=null && iter.hasNext()){
2917            Map.Entry entry = (Entry) iter.next();
2918            String vIDTBS = (String) entry.getKey();
2919            String routeTBS = (String) entry.getValue();
2920            TreeMap subMap = masterMap.get(routeTBS);
2921            if(subMap!=null){
2922                Object val = subMap.get(vIDTBS);
2923                if(val!=null){
2924                    if(vID==null){
2925                    degreeOfUserSatisfaction = degreeOfUserSatisfaction+Double.parseDouble(val.toString());
2926                    }else if(vID!=null && vID.equals(vIDTBS)){
2927                        degreeOfUserSatisfaction = Double.parseDouble(val.toString());
2928                        return degreeOfUserSatisfaction;
2929                    }
2930                }
2931            }
2932        }
2933    }
2934    return degreeOfUserSatisfaction;
2935}
2936
2937private static synchronized Map sortByComparator(Map unsortMap) {
2938
2939    List list = new LinkedList(unsortMap.entrySet());
2940
2941    //sort list based on comparator
2942    Collections.sort(list, new Comparator() {
2943         public int compare(Object o1, Object o2) {
2944           return ((Comparable) ((Map.Entry) (o2)).getValue())
2945           .compareTo(((Map.Entry) (o1)).getValue());
2946         }
2947    });
2948
2949    //put sorted list into map again
2950    Map sortedMap = new LinkedHashMap();
2951    for (Iterator it = list.iterator(); it.hasNext();) {
2952     Map.Entry entry = (Map.Entry)it.next();
2953     sortedMap.put(entry.getKey(), entry.getValue());
2954    }
2955    return sortedMap;
2956}
2957
2958public static double getLowestUtility(ConcurrentHashMap routeChoice)
2959{
2960    double lowestUtility=0.0;
2961    int cnt=0;
2962    ConcurrentHashMap rtCost = QueueManager.evaluateCostMap(routeChoice);
2963    if(routeChoice!=null){
2964    Set routeChoiceSet = routeChoice.entrySet();
2965    if(routeChoiceSet!=null){
2966        Iterator iter = routeChoiceSet.iterator();
2967        while(iter!=null && iter.hasNext()){
2968            Map.Entry entry = (Entry) iter.next();
2969            String vIDTBS = (String) entry.getKey();
2970            String routeTBS = (String) entry.getValue();
2971            TreeMap subMap = masterMap.get(routeTBS);
2972            if(subMap!=null){
2973                Object val = subMap.get(vIDTBS);
2974                Object ct = rtCost.get(routeTBS);
2975                if(val!=null && ct!=null){
2976                    double utility=Double.parseDouble(val.toString())-Double.parseDouble(ct.toString());
2977
2978                    if(cnt==0){
2979                    lowestUtility = utility;
2980                    cnt++;
2981                    }else{
2982                        if(utility<lowestUtility){
2983                            lowestUtility = utility;
2984                        }
2985                    }
2986                }
2987            }
2988        }
2989    }
2990}//routeChoice!=null
2991    return lowestUtility;
2992}
2993
2994
2995public static int getZeroCount(ConcurrentHashMap routeChoice)
2996{
2997
2998    int cnt=0;
2999    ConcurrentHashMap rtCost = QueueManager.evaluateCostMap(routeChoice);
3000
3001    Set routeChoiceSet = routeChoice.entrySet();
3002    if(routeChoiceSet!=null){
3003        Iterator iter = routeChoiceSet.iterator();
3004        while(iter!=null && iter.hasNext()){
3005            Map.Entry entry = (Entry) iter.next();
3006            String vIDTBS = (String) entry.getKey();
3007            String routeTBS = (String) entry.getValue();
3008            TreeMap subMap = masterMap.get(routeTBS);
3009            if(subMap!=null){
3010                Object val = subMap.get(vIDTBS);
3011                Object ct = rtCost.get(routeTBS);
3012                if(val!=null && ct!=null){
3013                    double utility=Double.parseDouble(val.toString())+Double.parseDouble(ct.toString());
3014                    if(utility==0.0){
3015                    cnt++;
3016                    }
3017                }
3018            }
3019        }
3020    }
3021    return cnt;
3022}
3023
3024/**
3025 * This method is used to retrieve the path based on route ID
3026 * @param vRouteID route ID
3027 * @return path of the vehicle
3028 */
3029public static synchronized String selectPathFromRouteID(String vRouteID) {
3030    String str = "select path from route where pathID = "+Integer.parseInt(vRouteID);
3031    ResultSet rsSelectAltPath = null;
3032    String vehPath = null;
3033
3034    try
3035    {
3036        PreparedStatement st = null;
3037        //System.out.println("Path ste: "+str);
3038        st = QueueManager.getConnection().prepareStatement(str);
3039        rsSelectAltPath = st.executeQuery();
3040
3041        while(rsSelectAltPath!=null && rsSelectAltPath.next())
3042        {
3043        vehPath = rsSelectAltPath.getString(1);
3044
3045        }
3046        st.close();
3047
3048
3049
3050    } catch (SQLException e) {
3051        e.printStackTrace();
3052    }
3053
3054    return vehPath;
3055}
3056
3057
3058public static synchronized int selectRoadCapacity(String vRouteID) {
3059    String str = "select path from route where pathID="+Integer.parseInt(vRouteID);
3060    ResultSet rsSelectAltPath = null;
3061    String vehPath = null;
3062    int rdCap = 0;
3063    try
3064    {
3065        PreparedStatement st = null;
3066        //System.out.println("Path ste: "+str);
3067        st = QueueManager.getConnection().prepareStatement(str);
3068        rsSelectAltPath = st.executeQuery();
3069
3070        while(rsSelectAltPath!=null && rsSelectAltPath.next())
3071        {
3072        vehPath = rsSelectAltPath.getString(1);
3073
3074        }
3075        st.close();
3076
3077        rdCap = getRoadCapacity(vehPath);
3078
3079
3080    } catch (SQLException e) {
3081        e.printStackTrace();
3082    }
3083
3084    return rdCap;
3085}
3086
3087
3088public static synchronized String getRIQPath(String localName,String xCoordinatesOfEdge, String yCoordinatesOfEdge) {
3089    String str = "select segmentID from junctionsegment where junctionID in (select junctionID from junctions where JNYCOORD="+yCoordinatesOfEdge+ "and JNXCOORD="+xCoordinatesOfEdge+")";
3090    ResultSet rsSelectAltPath = null;
3091    String vehPath = null;
3092    int rdCap = 0;
3093    try
3094    {
3095        PreparedStatement st = null;
3096        //System.out.println("Path ste: "+str);
3097        st = QueueManager.getConnection().prepareStatement(str);
3098        rsSelectAltPath = st.executeQuery();
3099
3100        while(rsSelectAltPath!=null && rsSelectAltPath.next())
3101        {
3102        vehPath = rsSelectAltPath.getString(1);
3103
3104        }
3105        st.close();
3106
3107
3108
3109    } catch (SQLException e) {
3110        e.printStackTrace();
3111    }
3112    if(vehPath==null){
3113//      System.out.println("For query string : "+str);
3114    }
3115    return vehPath;
3116
3117
3118}
3119
3120
3121/**
3122 * This method returns the congested segment ID based on the x and y coordinates
3123 * @param xCoord x coordinate
3124 * @param yCoord y coordinate
3125 * @return segment ID
3126 */
3127public static synchronized String getTheCongSeg(String xCoord, String yCoord){
3128    if(xCoord!=null && yCoord!=null){
3129        if(xCoord.equals("12.0") && yCoord.equals("8.0")){
3130            return "s1";
3131        }else if(xCoord.equals("24.5") && yCoord.equals("21.0")){
3132            return "s2";
3133        }/*else if(xCoord.equals("11.0") && yCoord.equals("47.0")){
3134            return "s37";
3135        }else if(xCoord.equals("46.5") && yCoord.equals("41.0")){
3136            return "s24";
3137        }else if(xCoord.equals("17.0") && yCoord.equals("55.0")){
3138            return "s39";
3139        }else if(xCoord.equals("22.5") && yCoord.equals("90.0")){
3140            return "s43";
3141        }else if(xCoord.equals("43.0") && yCoord.equals("84.5")){
3142            return "s27";
3143        }else if(xCoord.equals("83.0") && yCoord.equals("129.0")){
3144            return "s10";
3145        }/*else if(xCoord.equals("96.5") && yCoord.equals("232.0")){
3146        return "s17";
3147        }else if(xCoord.equals("71.0") && yCoord.equals("131.0")){
3148            return "s31";
3149        }else if(xCoord.equals("83.0") && yCoord.equals("129.0")){
3150            return "s11";
3151        }*/
3152
3153        }
3154
3155    return null;
3156}
3157
3158
3159}
3160
3161
3162
3163
3164
3165
3166
3167