public static Route getRoute( String method, String path, String action, String params, String headers, String sourceFile, int line) { Route route = new Route(); route.method = method; route.path = path.replace("//", "/"); route.action = action; route.routesFile = sourceFile; route.routesFileLine = line; route.addFormat(headers); route.addParams(params); route.compute(); if (Logger.isTraceEnabled()) { Logger.trace( "Adding [" + route.toString() + "] with params [" + params + "] and headers [" + headers + "]"); } return route; }
// Option 5 public void shortestByHops(String c1, String c2) { System.out.println("FEWEST HOPS from " + c1 + " to " + c2); System.out.println("---------------------------------------------"); City city1 = null; City city2 = null; for (int i = 0; i < numCities; i++) { if (cities[i].name().equals(c1)) { city1 = cities[i]; } if (cities[i].name().equals(c2)) { city2 = cities[i]; } } if (c1.equals(c2) || city1 == null || city2 == null) { System.out.println("Invalid city choice(s)"); return; } marked = new boolean[numCities]; distTo = new int[numCities]; edgeTo = new Route[numCities]; for (int i = 0; i < numCities; i++) distTo[i] = Integer.MAX_VALUE; bfs(city1.id() - 1); if (distTo[city2.id() - 1] == Integer.MAX_VALUE) { System.out.println("No path"); return; } System.out.printf("Fewest hops from %s to %s is %d\n", c1, c2, distTo[city2.id() - 1]); City currCity = city2; for (Route r = edgeTo[city2.id() - 1]; r != null; r = edgeTo[currCity.id() - 1]) { System.out.print(currCity + " "); currCity = r.other(currCity); } System.out.println(currCity); }
// Option 10 public void removeCity(String c) { City city = null; for (int i = 0; i < numCities; i++) { if (cities[i].name().equals(c)) { city = cities[i]; } } if (city == null) { System.out.println("Invalid city choice"); return; } // Remove all routes connected to the city for (Route r : adj[city.id() - 1]) { City other = r.other(city); adj[other.id() - 1].remove(r); routes.remove(r); numRoutes--; } cities[city.id() - 1] = null; adj[city.id() - 1] = null; numCities--; // Shift and resize arrays as necessary shiftCities(city.id() - 1); shiftAdj(city.id() - 1); if (numCities < cities.length / 2) { // halve the lengths of the arrays resizeCities(cities.length / 2); resizeAdj(cities.length / 2); } }
// relax edge e and update pq if changed private void relaxC(Route r, int v) { City city2 = r.other(cities[v]); int w = city2.id() - 1; if (costTo[w] > costTo[v] + r.price()) { costTo[w] = costTo[v] + r.price(); edgeTo[w] = r; if (costPQ.contains(w)) costPQ.change(w, costTo[w]); else costPQ.insert(w, costTo[w]); } }
/** * Dynamically find all {@link MllpTransactionEndpoint} containing a reference to this instance * and append it to the routeId list * * @param camelContext camel context */ private void collectTransactionTargets(CamelContext camelContext) { for (Route route : camelContext.getRoutes()) { if (route.getEndpoint() instanceof MllpTransactionEndpoint) { MllpTransactionEndpoint<?> endpoint = (MllpTransactionEndpoint<?>) route.getEndpoint(); if (endpoint.getDispatcher() == this) { addTransactionRoutes(route.getId()); } } } }
public static Map<String, String> route(String method, String path, String headers, String host) { for (Route route : routes) { Map<String, String> args = route.matches(method, path, headers, host); if (args != null) { args.put("action", route.action); return args; } } return new HashMap<String, String>(16); }
private void relaxD(Route r, int v) { // relax edge e and update pq if changed City city2 = r.other(cities[v]); int w = city2.id() - 1; if (distTo[w] > distTo[v] + r.distance()) { distTo[w] = distTo[v] + r.distance(); edgeTo[w] = r; if (pq.contains(w)) pq.change(w, distTo[w]); else pq.insert(w, distTo[w]); } }
// Option 1 public void showAllRoutes() { System.out.println("SHOWING ALL DIRECT ROUTES"); System.out.println( "Note that routes are duplicated," + " once from each end city's point of view"); System.out.println( "--------------------------------" + "-----------------------------------------"); Object[] objArr = routes.toArray(); for (int i = 0; i < numRoutes; i++) { Route route = (Route) objArr[i]; System.out.println(route.toStringWN()); } }
private void prim(int s, StringBuilder sb) { distTo[s] = 0; pq.insert(s, distTo[s]); while (!pq.isEmpty()) { int v = pq.delMin(); if (v != s) { Route r = edgeTo[v]; String str = String.format("%s, %s : %d\n", r.fst(), r.snd(), r.distance()); sb.append(str); } scan(v); } }
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) { if (mRoutes == null) { mRoutes = RoutesParser.init(mContext, mRouteRes); } for (Route r : mRoutes) { if (r.matches(request)) { return r.generateResponse(mContext, request); } } return ResponseGenerator.FACTORY.newHttpResponse(HTTP_1_1, 404, ResponseGenerator.CONTEXT); }
private Route findRoute(Request request) throws Exception { for (Route r : routeProvider.getRoutes()) { // TODO getBodyAsStream creates ByteArray each call. That could be a performance issue. Using // BufferedInputStream did't work, because stream got closed. if ((Boolean) newXPath(namespaces) .evaluate( r.getxPath(), new InputSource(request.getBodyAsStream()), XPathConstants.BOOLEAN)) return r; log.debug("no match found for xpath {" + r.getxPath() + "}"); } return null; }
public void removeRoute(City city1, City city2) { Route route = null; for (Route r : adj[city1.id() - 1]) { if (r.other(city1).equals(city2)) { route = r; break; } } adj[city1.id() - 1].remove(route); adj[city2.id() - 1].remove(route); routes.remove(route); numRoutes--; }
/** Order is important when comparing route lists. */ public boolean equals(Object other) { if (!(other instanceof RouteList)) return false; RouteList that = (RouteList) other; if (this.size() != that.size()) return false; ListIterator<Route> it = this.listIterator(); ListIterator<Route> it1 = that.listIterator(); while (it.hasNext()) { Route route = (Route) it.next(); Route route1 = (Route) it1.next(); if (!route.equals(route1)) return false; } return true; }
@Override public Outcome handleRequest(Exchange exc) throws Exception { if (exc.getRequest().isBodyEmpty()) { return Outcome.CONTINUE; } Route r = findRoute(exc.getRequest()); if (r == null) { return Outcome.CONTINUE; } log.debug("match found for {" + r.getxPath() + "} routing to {" + r.getUrl() + "}"); updateDestination(exc, r); return Outcome.CONTINUE; }
private Route reconstructPath() { FakeNode currentNode = endNode; Route route = new Route(); while (currentNode != null) { if (!route.prependNode(currentNode.node)) { System.err.println("Detected circular reference! Aborting ......"); throw new IllegalStateException("Detected circular reference!"); } currentNode = currentNode.cameFrom; } cleanUp(); return route; }
public static void main(String args[]) throws IOException { NetworkVersion nv = new NetworkVersion(2, ""); System.out.println("Solution#1"); nv.searchLines(); System.out.println("Solution#2"); for (int i = 0; i < nv.getLines().size(); i++) { nv.getLines().get(i).searchRoutes(); } System.out.println("Solution#3"); Route r = new Route(2, 1, 1); r.getStopAreas().get(0).searchStopPoints(); }
public static void routeOnlyStatic(Http.Request request) { for (Route route : routes) { try { if (route.matches(request.method, request.path, request.format, request.domain) != null) { break; } } catch (Throwable t) { if (t instanceof RenderStatic) { throw (RenderStatic) t; } if (t instanceof NotFound) { throw (NotFound) t; } } } }
public static Route route(Http.Request request) { if (Logger.isTraceEnabled()) { Logger.trace("Route: " + request.path + " - " + request.querystring); } // request method may be overriden if a x-http-method-override parameter is given if (request.querystring != null && methodOverride.matches(request.querystring)) { Matcher matcher = methodOverride.matcher(request.querystring); if (matcher.matches()) { if (Logger.isTraceEnabled()) { Logger.trace( "request method %s overriden to %s ", request.method, matcher.group("method")); } request.method = matcher.group("method"); } } for (Route route : routes) { Map<String, String> args = route.matches(request.method, request.path, request.format, request.domain); if (args != null) { request.routeArgs = args; request.action = route.action; if (args.containsKey("format")) { request.format = args.get("format"); } if (request.action.indexOf("{") > -1) { // more optimization ? for (String arg : request.routeArgs.keySet()) { request.action = request.action.replace("{" + arg + "}", request.routeArgs.get(arg)); } } if (request.action.equals("404")) { throw new NotFound(route.path); } return route; } } // Not found - if the request was a HEAD, let's see if we can find a corresponding GET if (request.method.equalsIgnoreCase("head")) { request.method = "GET"; Route route = route(request); request.method = "HEAD"; if (route != null) { return route; } } throw new NotFound(request.method, request.path); }
public void bfs(int s) { Queue<Integer> q = new Queue<Integer>(); distTo[s] = 0; marked[s] = true; q.enqueue(s); while (!q.isEmpty()) { int v = q.dequeue(); for (Route r : adj[v]) { int w = r.other(cities[v]).id() - 1; // index of other city on route if (!marked[w]) { edgeTo[w] = r; distTo[w] = distTo[v] + 1; marked[w] = true; q.enqueue(w); } } } }
private void scan(int v) { marked[v] = true; for (Route r : adj[v]) { int w = r.other(cities[v]).id() - 1; // index of other city in route if (marked[w]) { continue; // v-w is obsolete edge } if (r.distance() < distTo[w]) { distTo[w] = r.distance(); edgeTo[w] = r; if (pq.contains(w)) { pq.change(w, distTo[w]); } else { pq.insert(w, distTo[w]); } } } }
// Option 3 public void shortestByDistance(String c1, String c2) { System.out.println("SHORTEST DISTANCE PATH from " + c1 + " to " + c2); System.out.println("--------------------------------------------------------"); City city1 = null; City city2 = null; for (int i = 0; i < numCities; i++) { if (cities[i].name().equals(c1)) { city1 = cities[i]; } if (cities[i].name().equals(c2)) { city2 = cities[i]; } } if (c1.equals(c2) || city1 == null || city2 == null) { System.out.println("Invalid city choice(s)"); return; } distTo = new int[numCities]; edgeTo = new Route[numCities]; for (int i = 0; i < numCities; i++) distTo[i] = Integer.MAX_VALUE; distTo[city1.id() - 1] = 0; // relax vertices in order of distance from s pq = new IndexMinPQ<Integer>(numCities); pq.insert(city1.id() - 1, distTo[city1.id() - 1]); while (!pq.isEmpty()) { int v = pq.delMin(); for (Route r : adj[v]) relaxD(r, v); } if (distTo[city2.id() - 1] == Integer.MAX_VALUE) { System.out.println("No path"); return; } System.out.printf("Shortest distance from %s to %s is %d\n", c1, c2, distTo[city2.id() - 1]); System.out.println("Path with edges (in reverse order):"); City currCity = city2; for (Route r = edgeTo[city2.id() - 1]; r != null; r = edgeTo[currCity.id() - 1]) { System.out.print(currCity + " " + r.distance() + " "); currCity = r.other(currCity); } System.out.println(currCity); }
// Option 4 public void shortestByCost(String c1, String c2) { System.out.println("SHORTEST COST PATH from " + c1 + " to " + c2); System.out.println("--------------------------------------------------------"); City city1 = null; City city2 = null; for (int i = 0; i < numCities; i++) { if (cities[i].name().equals(c1)) { city1 = cities[i]; } if (cities[i].name().equals(c2)) { city2 = cities[i]; } } if (c1.equals(c2) || city1 == null || city2 == null) { System.out.println("Invalid city choice(s)"); return; } costTo = new double[numCities]; edgeTo = new Route[numCities]; for (int i = 0; i < numCities; i++) costTo[i] = Double.POSITIVE_INFINITY; costTo[city1.id() - 1] = 0; // relax vertices in order of distance from s costPQ = new IndexMinPQ<Double>(numCities); costPQ.insert(city1.id() - 1, costTo[city1.id() - 1]); while (!costPQ.isEmpty()) { int v = costPQ.delMin(); for (Route r : adj[v]) relaxC(r, v); } if (costTo[city2.id() - 1] == Double.POSITIVE_INFINITY) { System.out.println("No path"); return; } System.out.printf("Shortest cost from %s to %s is %.2f\n", c1, c2, costTo[city2.id() - 1]); System.out.println("Path with edges (in reverse order):"); City currCity = city2; for (Route r = edgeTo[city2.id() - 1]; r != null; r = edgeTo[currCity.id() - 1]) { System.out.print(currCity + " " + r.price() + " "); currCity = r.other(currCity); } System.out.println(currCity); }
private void recPaths(double maxCost, double currCost, City currCity) { // Backtrack if above max cost if (currCost > maxCost) { marked[currCity.id() - 1] = false; return; } // Print current path before continuing along routes if (edgeTo[currCity.id() - 1] != null) { System.out.printf("Cost: %.0f Path (reversed): ", currCost); City temp = currCity; for (Route r = edgeTo[temp.id() - 1]; r != null; r = edgeTo[temp.id() - 1]) { System.out.printf("%s %.0f ", temp, r.price()); temp = r.other(temp); } System.out.println(temp); } // Recursion marked[currCity.id() - 1] = true; for (Route r : adj[currCity.id() - 1]) { City other = r.other(currCity); // Don't follow route if other city already in path if (!marked[other.id() - 1]) { edgeTo[other.id() - 1] = r; recPaths(maxCost, currCost + r.price(), other); } } // traversed all paths from currCity, backtrack to previous city marked[currCity.id() - 1] = false; }
public void run() { if (!star) { System.out.println( "Run PCC de " + zoneOrigine + ":" + origine + " vers " + zoneDestination + ":" + destination); } if (star) { System.out.println( "Run PCC-Star de " + zoneOrigine + ":" + origine + " vers " + zoneDestination + ":" + destination); } // decision temps ou distance. Si on est en mode covoiturage, ce n'est pas nécessaire car on est // forcément en temps if (covoit == 0) { Scanner sc = new Scanner(System.in); System.out.println("En temps(0) ou distance(1)?"); if (sc.nextInt() == 1) { this.setdist(true); } } // chronometrage long start_time = System.currentTimeMillis(); Label l = new Label(false, 0.0, null, this.graphe.sommets.get(origine)); chem.add(l); tas.insert(l); maplabel.put(this.graphe.sommets.get(origine), l); // affichage de l'origine et de la destination this.graphe.getDessin().setColor(Color.BLUE); this.graphe .getDessin() .drawPoint( this.graphe.sommets.get(origine).getlon(), this.graphe.sommets.get(origine).getlat(), 10); this.graphe .getDessin() .drawPoint( this.graphe.sommets.get(destination).getlon(), this.graphe.sommets.get(destination).getlat(), 10); // compteur d'elements explores int nb_explor = 0; int tas_max = 0; while (!(tas.isEmpty())) { // extraction du minimum Label pere = tas.findMin(); tas.deleteMin(); // on arrete le programme une fois la destination trouvee, sauf si l'on ne souhaite pas // arreter ---> covoiturage if (pere.getCourant().getNum() == destination && (covoit == 0)) { System.out.println("Algorithme termine!"); break; } pere.setMarquage(true); chem.add(pere); for (Route route : pere.getCourant().routes) { Sommet suiv = route.getArrivee(); // affichage du parcours en temps reel. On ne le fait pas dans l'optimisation de covoiturage // car cela surcharge trop le dessin. if (this.getcovoit() == 0) { this.graphe.getDessin().setColor(Color.gray); this.graphe .getDessin() .drawLine( suiv.getlon(), suiv.getlat(), pere.getCourant().getlon(), pere.getCourant().getlat()); } // declarations des variables de cout, cout secondaire et estimation double new_cout = 0.0; double estim = 0.0; // ESTIMATION VERY IMPORTANT double cout_sec = 0.0; if (this.dist_temps) // Cout n distance { double vitesse = ((double) (route.getDesc().vitesseMax())); new_cout = pere.getCout() + ((double) (route.getDist())); // cout secondaire, ici en temps cout_sec = pere.getCoutSec() + (60.0 * ((double) (route.getDist())) / (1000.0 * vitesse)); if (this.star) { estim = suiv.dist_vol_oiseau(this.graphe.sommets.get(destination)); } } else { // Cout en temps double vitesse = ((double) (route.getDesc().vitesseMax())); // cas du pieton if (this.getcovoit() == 1 && (vitesse == 130.0 || vitesse == 110.0)) { // ici, le pieton ne peut pas acceder a cette route, // elle est reservee aux voitures, le cout est donc le plus grand possible new_cout = Double.MAX_VALUE; } else { if (this.getcovoit() == 1) { vitesse = 4.0; } new_cout = pere.getCout() + (60.0 * ((double) (route.getDist())) / (1000.0 * vitesse)); // cout secondaire, ici en distance cout_sec = pere.getCoutSec() + ((double) (route.getDist())); } // Ici on modifie le calcul de l'estimation dans le cas d'un calcul Astar. VERY IMPORTANT if (this.star) { estim = suiv.cout_vol_oiseau(this.graphe.sommets.get(destination), this.graphe.getvitmax()); } } // on regarde si le sommet a deja un label associe avec un cout different de l'infini) // pour ce faire, on verifie juste qu'il est integre a la hashmap ou pas if (maplabel.containsKey(suiv)) { maplabel.get(suiv).setEstim(estim); // maj du label, et de la hashmap // on ne verifie pas si le sommet est marque : en effet, s'il l'est, son cout // est deja minimal et la condition suivante sera toujours fausse. if (maplabel.get(suiv).getCout() > new_cout) { maplabel.get(suiv).setCout(new_cout); maplabel.get(suiv).setPere(pere.getCourant()); maplabel.get(suiv).setCoutSec(cout_sec); tas.update(maplabel.get(suiv)); } } else { // le sommet a un cout infini : on cree un label, et on l'integre a la hashmap Label lab = new Label(false, new_cout, pere.getCourant(), suiv); lab.setEstim(estim); lab.setCoutSec(cout_sec); tas.insert(lab); maplabel.put(suiv, lab); // compteurs de performance nb_explor++; if (tas.size() > tas_max) { tas_max = tas.size(); } } } } // on affiche le chemin this.print_chemin(this.graphe.sommets.get(destination)); // fin du chronometre long end_time = System.currentTimeMillis(); long difference = end_time - start_time; // on affiche les performances System.out.println("Temps écoulé en millisecondes : " + difference); System.out.println("Elements explorés : " + nb_explor); System.out.println("Taille max du tas : " + tas_max); }
public static ActionDefinition reverse(String action, Map<String, Object> args) { String encoding = Http.Response.current() == null ? Play.defaultWebEncoding : Http.Response.current().encoding; if (action.startsWith("controllers.")) { action = action.substring(12); } Map<String, Object> argsbackup = new HashMap<String, Object>(args); // Add routeArgs if (Scope.RouteArgs.current() != null) { for (String key : Scope.RouteArgs.current().data.keySet()) { if (!args.containsKey(key)) { args.put(key, Scope.RouteArgs.current().data.get(key)); } } } for (Route route : routes) { if (route.actionPattern != null) { Matcher matcher = route.actionPattern.matcher(action); if (matcher.matches()) { for (String group : route.actionArgs) { String v = matcher.group(group); if (v == null) { continue; } args.put(group, v.toLowerCase()); } List<String> inPathArgs = new ArrayList<String>(16); boolean allRequiredArgsAreHere = true; // les noms de parametres matchent ils ? for (Route.Arg arg : route.args) { inPathArgs.add(arg.name); Object value = args.get(arg.name); if (value == null) { // This is a hack for reverting on hostname that are a regex expression. // See [#344] for more into. This is not optimal and should retough. However, // it allows us to do things like {(.*}}.domain.com String host = route.host.replaceAll("\\{", "").replaceAll("\\}", ""); if (host.equals(arg.name) || host.matches(arg.name)) { args.remove(arg.name); route.host = Http.Request.current() == null ? "" : Http.Request.current().domain; break; } else { allRequiredArgsAreHere = false; break; } } else { if (value instanceof List<?>) { @SuppressWarnings("unchecked") List<Object> l = (List<Object>) value; value = l.get(0); } if (!value.toString().startsWith(":") && !arg.constraint.matches(value.toString())) { allRequiredArgsAreHere = false; break; } } } // les parametres codes en dur dans la route matchent-ils ? for (String staticKey : route.staticArgs.keySet()) { if (staticKey.equals("format")) { if (!(Http.Request.current() == null ? "" : Http.Request.current().format) .equals(route.staticArgs.get("format"))) { allRequiredArgsAreHere = false; break; } continue; // format is a special key } if (!args.containsKey(staticKey) || (args.get(staticKey) == null) || !args.get(staticKey).toString().equals(route.staticArgs.get(staticKey))) { allRequiredArgsAreHere = false; break; } } if (allRequiredArgsAreHere) { StringBuilder queryString = new StringBuilder(); String path = route.path; String host = route.host; if (path.endsWith("/?")) { path = path.substring(0, path.length() - 2); } for (Map.Entry<String, Object> entry : args.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (inPathArgs.contains(key) && value != null) { if (List.class.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") List<Object> vals = (List<Object>) value; path = path.replaceAll("\\{(<[^>]+>)?" + key + "\\}", vals.get(0).toString()) .replace("$", "\\$"); } else { path = path.replaceAll( "\\{(<[^>]+>)?" + key + "\\}", value .toString() .replace("$", "\\$") .replace("%3A", ":") .replace("%40", "@")); host = host.replaceAll( "\\{(<[^>]+>)?" + key + "\\}", value .toString() .replace("$", "\\$") .replace("%3A", ":") .replace("%40", "@")); } } else if (route.staticArgs.containsKey(key)) { // Do nothing -> The key is static } else if (Scope.RouteArgs.current() != null && Scope.RouteArgs.current().data.containsKey(key)) { // Do nothing -> The key is provided in RouteArgs and not used (see #447) } else if (value != null) { if (List.class.isAssignableFrom(value.getClass())) { @SuppressWarnings("unchecked") List<Object> vals = (List<Object>) value; for (Object object : vals) { try { queryString.append(URLEncoder.encode(key, encoding)); queryString.append("="); if (object.toString().startsWith(":")) { queryString.append(object.toString()); } else { queryString.append(URLEncoder.encode(object.toString() + "", encoding)); } queryString.append("&"); } catch (UnsupportedEncodingException ex) { } } } else if (value.getClass().equals(Default.class)) { // Skip defaults in queryString } else { try { queryString.append(URLEncoder.encode(key, encoding)); queryString.append("="); if (value.toString().startsWith(":")) { queryString.append(value.toString()); } else { queryString.append(URLEncoder.encode(value.toString() + "", encoding)); } queryString.append("&"); } catch (UnsupportedEncodingException ex) { } } } } String qs = queryString.toString(); if (qs.endsWith("&")) { qs = qs.substring(0, qs.length() - 1); } ActionDefinition actionDefinition = new ActionDefinition(); actionDefinition.url = qs.length() == 0 ? path : path + "?" + qs; actionDefinition.method = route.method == null || route.method.equals("*") ? "GET" : route.method.toUpperCase(); actionDefinition.star = "*".equals(route.method); actionDefinition.action = action; actionDefinition.args = argsbackup; actionDefinition.host = host; return actionDefinition; } } } } throw new NoRouteFoundException(action, args); }
private void updateDestination(Exchange exc, Route r) { exc.setOriginalRequestUri(r.getUrl()); exc.getDestinations().clear(); exc.getDestinations().add(r.getUrl()); }