public Set<Annotation> getObservedQualifiers() { Set<Annotation> as = new HashSet<Annotation>(); as.addAll(route.getQualifiers()); as.add(EGRESS); log.debugf("Inidicating that I observe these qualifiers: [%s]", as); return route.getQualifiers(); }
// 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); } }
private static void identifyRoutes(int routekey, int junction) { for (Road road : roaddetails) { if (junction == junctions) return; Route validRoute = null; if (road.startjunction == junction) { validRoute = validRoutes.get(routekey); if (validRoute == null || validRoute.isComplete) { validRoute = new Route(new HashSet<Road>()); routekey = road.roadidx; validRoute.routekey = routekey; validRoutes.put(routekey, validRoute); if (junction != 1) backTraceRouteAndComplete(routekey, road); } if (validRoute.isComplete) return; if (!validRoute.roads.contains(road)) { validRoute.roads.add(road); validRoute.totalcost += road.cost; road.routes.add(validRoute); } else continue; if (road.destjunction == junctions) validRoute.isComplete = true; identifyRoutes(routekey, road.destjunction); // if (junction!=1) // backTraceRouteAndComplete(routekey,junction); } } }
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); }
private synchronized void removePropertyChangeRoutes() { if (sysList != null) { for (Route route : sysList) { route.removePropertyChangeListener(this); } } }
/** * Helper method to turn a Collection of "Paths" into a Collection of Routes * * @param source * @param weights * @param prevNodes * @return */ private Map<Node, Route> makeRouteMap( Node source, Map<Node, Integer> weights, Map<Node, Node> prevNodes) { Map<Node, Route> routes = new HashMap<Node, Route>(); for (Map.Entry<Node, Integer> entry : weights.entrySet()) { Integer hops = 1; Node node = entry.getKey(); if (node.equals(source)) { continue; } Route route = new Route(); route.setDistance(entry.getValue()); Node nextHop = node; route.getPath().add(0, nextHop); while ((nextHop = prevNodes.get(nextHop)) != null) { if (nextHop.equals(source)) { continue; } hops++; route.getPath().add(0, nextHop); } route.setHops(hops); routes.put(node, route); } return routes; }
/** * Parse the parameter of route (content of request body). * * @param request http request. * @param route the route. * @return the parameters parsed. * @throws IOException in case of IO error. */ private Object getRouteParam(HttpServletRequest request, Route route) throws IOException { Object param = null; if (route.getParamType() != null && route.getParamType() != Void.class) { param = gson.fromJson(request.getReader(), route.getParamType()); } return param; }
/** * Handle a request. * * @param target The target of the request - either a URI or a name. * @param baseRequest The original unwrapped request object. * @param request The request either as the {@link Request} object or a wrapper of that request. * @param response The response as the {@link org.eclipse.jetty.server.Response} object or a * wrapper of that request. * @throws IOException in case of IO error. */ @SuppressWarnings("unchecked") @Override public void handle( String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { if (baseRequest.isHandled()) { return; } Route route = findRoute(request.getMethod(), request.getPathInfo()); if (route == null) { return; } Object param = getRouteParam(request, route); try { beginTransaction(); Response<?> handlerResponse = route.handle(param, new RouteParameters(route.getRouteParams(request.getPathInfo()))); commitTransaction(); writeHttpResponse(request, response, handlerResponse); } catch (HttpErrorException httpError) { commitTransaction(); writeHttpError(response, httpError); } catch (Exception exception) { rollBackTransaction(); writeInternalError(response, exception); } baseRequest.setHandled(true); }
public Route from(Node source) { Route route = new Route(); route.getPath().add(source); route.setDistance(0); route.setHops(0); return route; }
private void declareConsumers() throws IOException { for (final EndPointMethod endPointMethod : endPointMethods) { final RouteSpec routeSpec = endPointMethod.getRouteIn(); Route route = routeSpec.declareOn(channel, this); log.debug("consuming on " + route.getQueue() + " ==> " + endPointMethod); boolean autoAck = false; channel.basicConsume( route.getQueue(), autoAck, endPointMethod.toString(), new DefaultConsumer(channel) { @Override public void handleDelivery( String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String routingKey = envelope.getRoutingKey(); String contentType = properties.getContentType(); long deliveryTag = envelope.getDeliveryTag(); endPointMethod.call(new Event(Qarrot.this, channel, envelope, properties, body)); } }); } }
public void send( RouteSpec routeSpec, String routingKey, AMQP.BasicProperties properties, Object payload) throws IOException { Route route = routeSpec.declareOn(channel, this); route.publishOn( channel, routingKey, properties, toBytes(MediaTypes.valueOf(properties), payload)); }
/** Update the command signs to display the next player's name. */ private void updateSigns() { Set<Object[]> badSigns = new HashSet<Object[]>(); for (Object[] location : signs) { final World world = getServer().getWorld((String) location[0]); final int x = (Integer) location[1]; final int y = (Integer) location[2]; final int z = (Integer) location[3]; if (world.isChunkLoaded(x / 16, z / 16)) { final Block block = world.getBlockAt(x, y, z); final BlockState state = block.getState(); if (state instanceof Sign) { final Sign sign = (Sign) state; String token = sign.getLine(2); final Route route = routes.get(token.replaceAll(" ", "")); if (route != null) { String nextName = route.pickWinner(counter); if (nextName == null) { nextName = ChatColor.ITALIC + "No one"; } sign.setLine(3, nextName); sign.update(); } continue; // Avoid adding this to badSigns } badSigns.add(location); } } signs.removeAll(badSigns); counter++; }
public Route readLine(String line) throws IOException { Reader reader = new StringReader(line); int r = -1; while (state != null && (r = reader.read()) != -1) { char ch = (char) r; if (ch == COMMENT) { state.lineFinished(); state = null; } else { state = state.processChar(ch); } } if (state != null && r == -1) { state.lineFinished(); } // Checking if the line actually contained route definition if (route.getUrl().getUrlPattern() == null || !route.getUrl().getUrlPattern().trim().startsWith("/")) { return null; } else { return route; } }
/** * check the route is valid or not * * @return Route */ public Route findRoute(String departure, String destination) { for (int i = 0; i < routeList.size(); i++) { Route tempRoute = routeList.get(i); if (tempRoute.getDeparture() == departure && tempRoute.getDestination() == destination) return tempRoute; } return null; }
/** * find all route that contain that departure * * @param Departure String * @return Route ArrayList */ public ArrayList<Route> findRouteDepart(String departure) { ArrayList<Route> resultRoutes = new ArrayList<Route>(); for (int i = 0; i < routeList.size(); i++) { Route tempRoute = routeList.get(i); if (tempRoute.getDeparture().equals(departure)) resultRoutes.add(tempRoute); } return resultRoutes; }
/** * Add the route in the database if it's not already, or update its state. * * @param routes being added to the app */ @Override public void onRoutesAdd(Collection<Route> routes) { for (Route routeCamel : routes) { // adding a performance counter on the route if (routeCamel instanceof EventDrivenConsumerRoute) { EventDrivenConsumerRoute edcr = (EventDrivenConsumerRoute) routeCamel; Processor processor = edcr.getProcessor(); if (processor instanceof InstrumentationProcessor) { InstrumentationProcessor ip = (InstrumentationProcessor) processor; ConsolePerformanceCounter counter = new ConsolePerformanceCounter(routeCamel.getId(), repository); ip.setCounter(counter); log.debug("Adding a counter" + counter.toString() + " to " + routeCamel.getId()); } } // saving route in database log.debug("Route added " + routeCamel.getId()); com.ninja_squad.console.Route route = repository.findRoute(routeCamel.getId()); if (route == null) { route = new com.ninja_squad.console.Route(routeCamel.getId()) .state(State.Started) .uri(routeCamel.getEndpoint().getEndpointUri()); ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()); // make serializer use JAXB annotations (only) mapper.setAnnotationIntrospector(introspector); String definition = null; RouteDefinition routeDefinition = routeCamel.getRouteContext().getRoute(); try { definition = mapper.writeValueAsString(routeDefinition); } catch (IOException e) { log.error("Error while marshalling route definition", e); } route.setDefinition(definition); for (ProcessorDefinition<?> stepDefinition : routeDefinition.getOutputs()) { if (stepDefinition.getId() == null) { stepDefinition.setId(stepDefinition.getClass().getSimpleName()); } route.getSteps().put(stepDefinition.getId(), stepDefinition.getLabel()); } repository.save(route); } // saving state in database RouteState routeState = repository.lastRouteState(routeCamel.getId()); if (routeState == null || routeState.getState().equals(State.Stopped)) { routeState = new RouteState(); routeState.setRouteId(routeCamel.getId()); routeState.setState(State.Started); routeState.setTimestamp(DateTime.now().getMillis()); repository.save(routeState); } } }
@Test public void usePatternMatchingForRegexParameters() throws Exception { builder = newBuilder("/abc/{abc:a+b+c+}/def/{def}/ghi/{ghi}"); builder.is(MyResource.class, method.getMethod()); Route route = builder.build(); assertFalse("invalid uri", route.canHandle("/abc/itIsInvalid/def/123/ghi/123.45")); assertTrue("valid uri", route.canHandle("/abc/aaabbccccc/def/-123/ghi/-1")); }
public Response handleRequest(Request request) { for (Route route : routes) { Response response = route.handle(request); if (response.equals(Response.BODY_REQUIRED) || !response.equals(Response.CONTINUE)) { return response; } } return defaultHandler.handle(request); }
public Response handleRequest(Request request, RequestBody requestBody) { for (Route route : routes) { Response response = route.handle(request); if (!response.equals(Response.CONTINUE)) { return response; } } return defaultHandler.handle(request); }
/** * 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); }
// 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]); } }
/** * Change the experience reward for a route. * * @param sender Entity changing the reward * @param routeName Name of route to change * @param xp New amount of experience awarded on completion * @throws ExplorersException */ private void setxpCommand(CommandSender sender, String routeName, int xp) throws ExplorersException { if (!sender.hasPermission(REWARDS_PERMISSION)) { throw new ExplorersPermissionException(); } Route r = getExistingRoute(routeName); r.setXpAward(xp); sender.sendMessage(ChatColor.GREEN + "Success"); }
/** * Notify a player if they have completed this route and thus are able to use the protected block. * * @param player Player using the sign * @param routeName Route associated with the sign * @throws ExplorersException */ private void activateLockSign(Player player, String routeName) throws ExplorersException { Route r = getExistingRoute(routeName); if (r.isWinner(player)) { player.sendMessage(ChatColor.GREEN + "Unlocked"); } else { player.sendMessage(ChatColor.RED + "You have not completed this route."); } }
private void forwardEvent(Object event) { if (!this.route.isEgressEnabled()) return; MessageManager msgBuilder = this.getMessageBuilder(); if (event instanceof String) { msgBuilder.sendTextToDestinations( event.toString(), route.getDestinations().toArray(new Destination[] {})); } else { msgBuilder.sendObjectToDestinations( event, route.getDestinations().toArray(new Destination[] {})); } }
@Test public void fillingUriForPrimitiveParameters() throws Exception { builder = newBuilder("/abc/{abc}/def/{def}/ghi/{ghi}"); Method method = MyResource.class.getDeclaredMethods()[0]; builder.is(MyResource.class, method); Route route = builder.build(); String url = route.urlFor(MyResource.class, method, "Anything", 123, new BigDecimal("123.45")); assertThat(url, is("/abc/Anything/def/123/ghi/123.45")); }
@Test public void usingRegexesWithAsterisksAtTheEnd() throws Exception { builder = newBuilder("/abc/{abc:[0-9A-Z]*}/def/{def}"); builder.is(MyResource.class, method.getMethod()); Route route = builder.build(); assertFalse("invalid uri", route.canHandle("/abc/not_Valid/def/12")); assertTrue("valid uri", route.canHandle("/abc/ABC123/def/12")); assertTrue("valid uri", route.canHandle("/abc/10AB3/def/12")); }
@Test public void usingRegexesWithCurlyBracesNotOnTheEndAndOtherVar() throws Exception { builder = newBuilder("/abc/{abc:[0-9A-Z]{5}}/def/{def}"); builder.is(MyResource.class, method.getMethod()); Route route = builder.build(); assertFalse("invalid uri", route.canHandle("/abc/notValid/def/12")); assertFalse("invalid uri", route.canHandle("/abc/ABC123/def/12")); assertTrue("valid uri", route.canHandle("/abc/10AB3/def/12")); }
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]); } }