@Test public void doubleDouble() { Scenario scenario = new Scenario("Java API test"); scenario .surface() .apply() .shifts(ScenarioShiftType.RELATIVE, volShift(1.5, 6.0, 0.1), volShift(2.5, 1.0, 0.2)); ScenarioDefinition definition = scenario.createDefinition(); assertEquals("Java API test", definition.getName()); Map<DistinctMarketDataSelector, FunctionParameters> map = definition.getDefinitionMap(); FunctionParameters params = map.get(new VolatilitySurfaceSelector(null, null, null, null, null, null, null)); assertNotNull(params); Object value = ((SimpleFunctionParameters) params) .getValue(StructureManipulationFunction.EXPECTED_PARAMETER_NAME); CompositeStructureManipulator manipulator = (CompositeStructureManipulator) value; List manipulators = manipulator.getManipulators(); assertEquals(1, manipulators.size()); List<VolatilitySurfaceShift> shifts = ImmutableList.of( new VolatilitySurfaceShift(1.5, 6.0, 0.1), new VolatilitySurfaceShift(2.5, 1.0, 0.2)); VolatilitySurfaceShiftManipulator expected = VolatilitySurfaceShiftManipulator.create(ScenarioShiftType.RELATIVE, shifts); assertEquals(expected, manipulators.get(0)); }
public Message receive(Scenario scenario) throws Exception { Connection connection = null; try { ConnectionFactory factory = new ActiveMQConnectionFactory(scenario.getBrokerUrl()); connection = factory.createConnection(); connection.start(); Session session = null; try { session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge()); ActiveMQQueue destination = new ActiveMQQueue(scenario.getOutputQueue()); MessageConsumer consumer = null; try { consumer = session.createConsumer(destination); return scenario.receive(session, consumer); } finally { if (consumer != null) { consumer.close(); } } } finally { if (session != null) { session.close(); } } } finally { if (connection != null) { connection.close(); } } }
public void send(Scenario scenario) throws Exception { Connection connection = null; try { ConnectionFactory factory = new ActiveMQConnectionFactory(scenario.getBrokerUrl()); connection = factory.createConnection(); connection.start(); Session session = null; try { session = connection.createSession(scenario.isTransacted(), scenario.getAcknowledge()); ActiveMQQueue destination = new ActiveMQQueue(scenario.getInputQueue()); MessageProducer producer = null; try { producer = session.createProducer(destination); scenario.send(session, producer); } finally { if (producer != null) { producer.close(); } } } finally { if (session != null) { session.close(); } } } finally { if (connection != null) { connection.close(); } } }
/* * Liest die Scenario Informationen in die entsprechenden Objekte * und gibt eine Liste davon zurueck. Siehe dazu auch MeteringProcessStorage.java. * @param fileName Dateiname der Storagedatei * @return Liste mit den Scenario-Objekte. */ public List getList() { List scenariosList = new ArrayList(); try { SAXBuilder builder = new SAXBuilder(); StorageDoc = builder.build(appPath + storageFileName); Root = StorageDoc.getRootElement(); List scenarioChildren = Root.getChildren("scenario", ipfixConfigNS); Iterator listIterator = scenarioChildren.iterator(); Element currentElement; while (listIterator.hasNext()) { currentElement = (Element) listIterator.next(); Scenario currentScenario = new Scenario(); // currentscenario.setId(Integer.valueOf(currentElement.getAttributeValue("id"))); currentScenario.setName(currentElement.getChildText("name", ipfixConfigNS)); currentScenario.setDescription(currentElement.getChildText("descript", ipfixConfigNS)); List deviceList = new ArrayList(); Element devices = currentElement.getChild("devices", ipfixConfigNS); List childList = devices.getChildren("device", ipfixConfigNS); Iterator devicesIterator = childList.iterator(); while (devicesIterator.hasNext()) { Element currentDevice = (Element) devicesIterator.next(); deviceList.add(currentDevice.getText()); } currentScenario.setDeviceList(deviceList); scenariosList.add(currentScenario); } } catch (Exception ex) { ex.printStackTrace(); } return scenariosList; }
@Override public void addScenarios(Collection<Scenario> scenarios) { this.scenarios.addAll(scenarios); for (Scenario scenario : scenarios) { scenario.setGroup(title); } }
/** Make sure that stops are properly linked into the graph */ @Test public void testStopLinking() throws Exception { AddTripPattern atp = getAddTripPattern(RouteSelector.BROAD_HIGH); atp.timetables.add(getTimetable(true)); // get a graph Graph g = buildGraphNoTransit(); link(g); g.index(new DefaultStreetVertexIndexFactory()); // materialize the trip pattern atp.materialize(g); // there should be five stops because one point is not a stop assertEquals(5, atp.temporaryStops.length); // they should all be linked into the graph for (int i = 0; i < atp.temporaryStops.length; i++) { assertNotNull(atp.temporaryStops[i].sample); assertNotNull(atp.temporaryStops[i].sample.v0); assertNotNull(atp.temporaryStops[i].sample.v1); } // no services running: not needed for trips added on the fly. TimeWindow window = new TimeWindow(7 * 3600, 9 * 3600, new BitSet(), DayOfWeek.WEDNESDAY); Scenario scenario = new Scenario(0); scenario.modifications = Lists.newArrayList(atp); ProfileRequest req = new ProfileRequest(); req.scenario = scenario; req.boardingAssumption = RaptorWorkerTimetable.BoardingAssumption.WORST_CASE; RaptorWorkerData data = new RaptorWorkerData(g, window, req); assertEquals(5, data.nStops); // make sure we can find the stops AStar aStar = new AStar(); RoutingRequest rr = new RoutingRequest(TraverseMode.WALK); rr.from = new GenericLocation(39.963417, -82.980799); rr.batch = true; rr.setRoutingContext(g); rr.batch = true; ShortestPathTree spt = aStar.getShortestPathTree(rr); TIntIntMap stops = data.findStopsNear(spt, g); // we should have found stops assertFalse(stops.isEmpty()); // ensure that the times made it into the data // This assumes worst-case departure, and the first worst departure is 10:30 after the service // starts running (dwell + headway) assertEquals( 4 * 3600 + 600 + 30, data.timetablesForPattern.get(0).getFrequencyDeparture(0, 0, 39 * 360, -1, null)); }
@Test public void addCheckSameScenario() { Scenario scenario1 = new Scenario(); scenario1.setScenarioName("ABC"); Scenario scenario2 = new Scenario(); scenario2.setScenarioName("ABC"); assert (scenario1.hasSameNameAndResponse(scenario2)) : "Scenarios should be the same (match == true)"; }
@Override public void read(ConfigurationNode node, ConfigurationReader reader) throws ConfigurationException { title = reader.readStringAttribute(node, ConfigurationXml.ATTRIBUTE_TITLE); scenarios.addAll(readScenarios(node, reader)); for (Scenario scenario : scenarios) { scenario.setGroup(title); } }
@Test(expectedExceptions = IllegalArgumentException.class) public void dateDate() { Scenario scenario = new Scenario("Java API test"); scenario .surface() .apply() .shifts( ScenarioShiftType.RELATIVE, volShift(Period.ofYears(1), Period.ofMonths(6), 0.1), volShift(Period.ofYears(2), Period.ofMonths(9), 0.2)); }
/** * Act - do whatever the Notice wants to do. This method is called whenever the 'Act' or 'Run' * button gets pressed in the environment. */ public void act() { Scenario e = (Scenario) getWorld(); if (vel < 0) move(vel); vel--; if (getX() + getImage().getWidth() / 2 < 0) { if (fin == true) { if (e.getActualSound().isPlaying()) e.getActualSound().stop(); Greenfoot.setWorld(new Menu()); } else getWorld().removeObject(this); } }
@Override public void write(ConfigurationNode node, NodeFactory factory) { node.addAttribute(factory.createNode(ConfigurationXml.ATTRIBUTE_TITLE, title)); for (Scenario scenario : scenarios) { ConfigurationNode scenarioNode = factory.createNode(DefaultScenarioGroup.NODE_SCENARIO); scenario.write(scenarioNode, factory); node.addChild(scenarioNode); } }
private List<Scenario> getScenarios(InstallationType compatibility) { ArrayList<Scenario> result = new ArrayList<Scenario>(this.scenarios.size()); for (Scenario scenario : this.scenarios) { if (scenario == null) { continue; } if (compatibility.matches(scenario.getCompatibility())) { result.add(scenario); } } return result; }
public void execute(RequestModel requestModel) { Scenario scenario; if (requestModel.requestedScenarioIs(Scenarios.REST)) { scenario = new Rest(game, output); } else if (requestModel.requestedScenarioIs(Scenarios.MOVE)) { scenario = new MovePlayer(game, output, requestModel.getDirection()); } else if (requestModel.requestedScenarioIs(Scenarios.SHOOT)) { scenario = new ShootArrow(game, output, requestModel.getDirection()); } else { scenario = new UnknownCommand(game, output, requestModel.getUnknownCommand()); } scenario.invoke(); }
private static <T> void verifyScenario(Scenario<T> scenario, int level) { scenario.testCompareTo(); scenario.testIsOrdered(); scenario.testMinAndMax(); scenario.testBinarySearch(); scenario.testSortedCopy(); if (level < RECURSE_DEPTH) { for (OrderingMutation alteration : OrderingMutation.values()) { verifyScenario(alteration.mutate(scenario), level + 1); } } }
@Test public void checkAlphabeticOrderOfTags() { Scenario scenario = new Scenario(); String arg1 = "abc"; String arg2 = "def"; String arg3 = "xyz"; List<String> argList = new ArrayList<String>(); argList.add(arg1); argList.add(arg2); argList.add(arg3); scenario.setTagList(argList); assert (scenario.getTag().equals("abc def xyz")) : "Tag not alphabetic. Should have been 'abc def xyz' but was " + scenario.getTag(); }
/** * Read the scenarios of a node representing the scenario group. * * @param scenarioGroup * @return a list of scenarios configured within this scenario group that must not be <code>null * </code> * @throws ConfigurationException if a problem occur to read the XML nodes * @author martin.wurzinger */ private static List<Scenario> readScenarios( ConfigurationNode scenarioGroup, ConfigurationReader reader) throws ConfigurationException { List<Scenario> results = new ArrayList<Scenario>(); for (ConfigurationNode scenarioNode : reader.getChildren(scenarioGroup, DefaultScenarioGroup.NODE_SCENARIO)) { Scenario scenario = new DefaultScenario(); scenario.read(scenarioNode, reader); results.add(scenario); } return results; }
protected IScenario getDefaultScenario() { IScenario scenario; try { scenario = Scenario.load(); if (scenario == null) { scenario = Scenario.getDefault(); } } catch (Exception ex) { scenario = Scenario.getDefault(); } return scenario; }
/** Test run of whole scenario. */ @Test public void runningWholeScenario() { final NopHandler<?> handler = new NopHandler<>(); @SuppressWarnings("unchecked") final Simulator sim = Simulator.builder() .setTickLength(1L) .setTimeUnit(SI.SECOND) .addModel( ScenarioController.builder(scenario) .withNumberOfTicks(-1) .withEventHandler(EventA.class, (NopHandler<EventA>) handler) .withEventHandler(EventB.class, (NopHandler<EventB>) handler) .withEventHandler(EventC.class, (NopHandler<EventC>) handler)) .build(); controller = sim.getModelProvider().getModel(ScenarioController.class); controller .getEventAPI() .addListener( new Listener() { @Override public void handleEvent(Event e) { if (e.getEventType() == ScenarioController.EventType.SCENARIO_FINISHED) { sim.stop(); } } }); sim.start(); assertThat(handler.getEvents()).hasSize(scenario.getEvents().size()); assertThat(controller.isScenarioFinished()).isTrue(); }
private static String checkTestNamesUnique(Map<String, List<Scenario>> scenarioMap) { StringBuilder stringBuilder = new StringBuilder(); for (String feature : scenarioMap.keySet()) { List<Scenario> scenarios = scenarioMap.get(feature); for (Scenario scenario : scenarios) { for (Scenario scenario1 : scenarios) { if (!scenario1.equals(scenario) && scenario1.getScenarioName().startsWith(scenario.getScenarioName())) { stringBuilder .append("Feature '") .append(feature) .append("' scenario '") .append(scenario.getScenarioName()) .append("' name crosses with scenario '") .append(scenario1.getScenarioName()) .append("'"); stringBuilder.append("\n"); } } } } String result = stringBuilder.toString(); if (result.length() > 0) { return result; } return null; }
@Override public void play() { Intent intent = new Intent("pl.jasiun.SMS_RECEIVER_SETTINGS_APPEARED"); Bundle extras = new Bundle(); extras.putString("SENDER", sender); extras.putString("PATTERN", pattern); intent.putExtras(extras); scenario.getStageManager().sendIntent(intent); }
private ScenarioModel namedScenario(Description description) { Scenario scenarioAnnotation = description.getAnnotation(Scenario.class); Parameters parametersAnnotation = description.getAnnotation(Parameters.class); String name = null; if (scenarioHasDefinedName(scenarioAnnotation)) name = scenarioAnnotation.value(); else name = createScenarioNameFromTestMethodName(description, parametersAnnotation); if (parametersAnnotation != null && !scenarioAnnotation.pending()) name = name.substring(name.indexOf('(') + 1, name.indexOf(')')) + " (" + description .getMethodName() .substring(0, description.getMethodName().indexOf('(') - 1) + ")"; return ScenarioManager.currentScenario().withName(name).withDescription(description); }
/* package */ VolatilitySurfaceSelector getSelector() { return new VolatilitySurfaceSelector( _scenario.getCalcConfigNames(), _names, _nameMatchPattern, _nameLikePattern, _instrumentTypes, _quoteTypes, _quoteUnits); }
/** Tests creating index shifts from a Groovy script. */ @Test public void index() { Scenario scenario = SimulationUtils.createScenarioFromDsl("src/test/groovy/SurfaceTest3.groovy", null); ScenarioDefinition definition = scenario.createDefinition(); assertEquals("surface index shifts", definition.getName()); Map<DistinctMarketDataSelector, FunctionParameters> map = definition.getDefinitionMap(); FunctionParameters params = map.get(new VolatilitySurfaceSelector(null, null, null, null, null, null, null)); assertNotNull(params); Object value = ((SimpleFunctionParameters) params) .getValue(StructureManipulationFunction.EXPECTED_PARAMETER_NAME); CompositeStructureManipulator manipulator = (CompositeStructureManipulator) value; List manipulators = manipulator.getManipulators(); assertEquals(1, manipulators.size()); List<Double> shifts = Lists.newArrayList(0d, 1e-4, 2e-4); VolatilitySurfaceIndexShifts expected = new VolatilitySurfaceIndexShifts(ScenarioShiftType.ABSOLUTE, shifts); assertEquals(expected, manipulators.get(0)); }
public DBOutputWriter(Scenario scenario) { super(scenario); try { db_scenario = ScenariosPeer.retrieveByPK(str2id(scenario.getId())); } catch (NoRowsException exc) { logger.error("Scenario " + str2id(scenario.getId()) + " was not found in the database"); } catch (TooManyRowsException exc) { logger.error("Data integrity violation", exc); } catch (TorqueException exc) { logger.error("Could not load scenario " + str2id(scenario.getId()), exc); } db_vehicle_type = new VehicleTypes[scenario.getNumVehicleTypes()]; if (null != db_scenario) { logger.info("Loading vehicle types"); Criteria crit = new Criteria(); crit.addJoin(VehicleTypesPeer.VEHICLE_TYPE_ID, VehicleTypesInSetsPeer.VEHICLE_TYPE_ID); crit.add(VehicleTypesInSetsPeer.VEHICLE_TYPE_SET_ID, db_scenario.getVehicleTypeSetId()); try { @SuppressWarnings("unchecked") List<VehicleTypes> db_vt_l = VehicleTypesPeer.doSelect(crit); for (VehicleTypes db_vt : db_vt_l) for (int i = 0; i < scenario.getNumVehicleTypes(); ++i) if (db_vt.getName().equals(scenario.getVehicleTypeNames()[i])) db_vehicle_type[i] = db_vt; } catch (TorqueException exc) { logger.error("Failed to load vehicle types for scenario " + db_scenario.getId(), exc); } } }
/** * Creates a mock of the given type. * * <p>There is no .class literal for generic types. Therefore you need to pass the raw type when * mocking generic types. E.g. Mock<List<String>> myMock = new MockObject("myMock", * List.class, this); * * <p>If the mocked type does not correspond to the declared type, a ClassCastException will occur * when the mock is used. * * <p>If no name is given the un-capitalized type name + Mock is used, e.g. myServiceMock * * @param name The name of the mock, e.g. the field-name, null for the default * @param mockedType The mock type that will be proxied, use the raw type when mocking generic * types, not null * @param testObject The test object, not null */ @SuppressWarnings({"unchecked"}) public MockObject(String name, Class<?> mockedType, Object testObject) { if (isBlank(name)) { this.name = uncapitalize(mockedType.getSimpleName()) + "Mock"; } else { this.name = name; } this.mockedType = (Class<T>) mockedType; this.oneTimeMatchingBehaviorDefiningInvocations = createOneTimeMatchingBehaviorDefiningInvocations(); this.alwaysMatchingBehaviorDefiningInvocations = createAlwaysMatchingBehaviorDefiningInvocations(); this.chainedMocksPerName = new HashMap<String, Mock<?>>(); Scenario scenario = getScenario(testObject); if (scenario.getTestObject() != testObject) { scenario.reset(); getMatchingInvocationBuilder().reset(); scenario.setTestObject(testObject); } this.mockProxy = createMockProxy(); }
public void WriteScenario(Scenario scenario, String filename) throws IOException { BufferedWriter FR = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF-8")); // beginning of an XML file: FR.write("<?xml version=\"1.0\" encoding =\"UTF-8\"?>"); FR.newLine(); scenario.SerializeXML(FR); FR.newLine(); FR.close(); }
@Test public void absolute() { Scenario scenario = SimulationUtils.createScenarioFromDsl("src/test/groovy/SurfaceTest2.groovy", null); ScenarioDefinition definition = scenario.createDefinition(); assertEquals("absolute surface test", definition.getName()); Map<DistinctMarketDataSelector, FunctionParameters> map = definition.getDefinitionMap(); FunctionParameters params = map.get(new VolatilitySurfaceSelector(null, null, null, null, null, null, null)); assertNotNull(params); Object value = ((SimpleFunctionParameters) params) .getValue(StructureManipulationFunction.EXPECTED_PARAMETER_NAME); CompositeStructureManipulator manipulator = (CompositeStructureManipulator) value; List manipulators = manipulator.getManipulators(); assertEquals(1, manipulators.size()); List<VolatilitySurfaceShift> shifts = ImmutableList.of( new VolatilitySurfaceShift(0.5, 0.6, 0.1), new VolatilitySurfaceShift(1.5, 0.7, 0.2)); VolatilitySurfaceShiftManipulator expected = VolatilitySurfaceShiftManipulator.create(ScenarioShiftType.ABSOLUTE, shifts); assertEquals(expected, manipulators.get(0)); }
public static void main(String[] args) { String dir = "d:\\PP-rad\\poznan\\"; String networkFile = dir + "network.xml"; String linkStats = dir + "40.linkstats.txt.gz"; String polygonFile = dir + "poznan_polygon\\poznan_city_polygon.shp"; boolean includeBorderLinks = false; String filteredLinkStats = dir + "40.linkstats-filtered.txt.gz"; Geometry polygonGeometry = PolygonBasedFilter.readPolygonGeometry(polygonFile); Predicate<Link> linkInsidePolygonPredicate = PolygonBasedFilter.createLinkInsidePolygonPredicate(polygonGeometry, includeBorderLinks); Scenario scenario = ScenarioUtils.createScenario(VrpConfigUtils.createConfig()); MatsimNetworkReader nr = new MatsimNetworkReader(scenario); nr.readFile(networkFile); Map<Id<Link>, ? extends Link> linkMap = scenario.getNetwork().getLinks(); try (BufferedReader br = IOUtils.getBufferedReader(linkStats); PrintWriter pw = new PrintWriter(IOUtils.getBufferedWriter(filteredLinkStats))) { String header = br.readLine(); pw.println(header); String line; while ((line = br.readLine()) != null) { String linkId = new StringTokenizer(line).nextToken(); // linkId - first column Link link = linkMap.get(Id.create(linkId, Link.class)); if (linkInsidePolygonPredicate.apply(link)) { pw.println(line); } } } catch (IOException e) { throw new RuntimeException(e); } }
@Test public void addCheckNotSameScenario() { Scenario scenario1 = new Scenario(); scenario1.setScenarioName("ABC"); Scenario scenario2 = new Scenario(); scenario2.setScenarioName("ABC"); scenario2.setResponseMessage("xxx"); assert (!scenario1.hasSameNameAndResponse(scenario2)) : "Scenarios should NOT be the same (match == false)"; }
public void printContent(PrintWriter itsWriter, String delimiter) { Collection steps = getstepsValue(); if (steps != null) { for (Iterator i = steps.iterator(); i.hasNext(); ) { Object step = i.next(); if (step instanceof Scenario) { ((Scenario) step).printContent(itsWriter, delimiter); } } itsWriter.println(); for (Iterator j = steps.iterator(); j.hasNext(); ) { Object step = j.next(); if (step instanceof Action_Choice) { ((Action_Choice) step).printContent(itsWriter, delimiter); } } } }