@Test public void testReadBandRasterData() { Date startDate = Calendar.getInstance().getTime(); // Product product = new Product("name", "desc", 100, 200); File file = TestUtil.getTestFile( productsFolder + "SP04_HRI1_X__1O_20050605T090007_20050605T090016_DLR_70_PREU.BIL.ZIP"); // File rasterFile = TestUtil.getTestFile(productsFolder + "mediumImage.tif"); System.setProperty("snap.dataio.reader.tileWidth", "100"); System.setProperty("snap.dataio.reader.tileHeight", "200"); try { Product finalProduct = reader.readProductNodes(file, null); ProductData data = ProductData.createInstance(ProductData.TYPE_UINT16, 20000); data.setElemFloatAt(3, 5); reader.readBandRasterData( finalProduct.getBandAt(0), 2000, 2000, 100, 200, data, new NullProgressMonitor()); assertNotEquals(0, data.getElemFloatAt(0)); assertNotEquals(-1000, data.getElemFloatAt(0)); assertNotEquals(0, data.getElemFloatAt(1999)); assertNotEquals(-1000, data.getElemFloatAt(1999)); assertNotEquals(5, data.getElemFloatAt(3)); Date endDate = Calendar.getInstance().getTime(); assertTrue( "The load time for the product is too big!", (endDate.getTime() - startDate.getTime()) / (60 * 1000) < 30); } catch (IOException e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } }
@Test public void testContinueOnSomeDbDirectoriesMissing() throws Exception { File targetDir1 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); File targetDir2 = new File(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); try { assertTrue(targetDir1.mkdirs()); assertTrue(targetDir2.mkdirs()); if (!targetDir1.setWritable(false, false)) { System.err.println( "Cannot execute 'testContinueOnSomeDbDirectoriesMissing' because cannot mark directory non-writable"); return; } RocksDBStateBackend rocksDbBackend = new RocksDBStateBackend(TEMP_URI); rocksDbBackend.setDbStoragePaths(targetDir1.getAbsolutePath(), targetDir2.getAbsolutePath()); try { rocksDbBackend.initializeForJob(getMockEnvironment(), "foobar", IntSerializer.INSTANCE); } catch (Exception e) { e.printStackTrace(); fail("Backend initialization failed even though some paths were available"); } } finally { //noinspection ResultOfMethodCallIgnored targetDir1.setWritable(true, false); FileUtils.deleteDirectory(targetDir1); FileUtils.deleteDirectory(targetDir2); } }
@Before public void setUp() { System.setProperty("nhinc.properties.dir", System.getenv("NHINC_PROPERTIES_DIR")); // create first test PseudonymMap pseudonymMap_1 = new PseudonymMap(); pseudonymMap_1.setPseudonymPatientId(pseudoPatientId_1); pseudonymMap_1.setPseudonymPatientIdAssigningAuthority(pseudoAuthorityId_1); pseudonymMap_1.setRealPatientId(realPatientId_1); pseudonymMap_1.setRealPatientIdAssigningAuthority(realAuthorityId_1); // create second test PseudonymMap - only difference is pseudoPatientId pseudonymMap_2 = new PseudonymMap(); pseudonymMap_2.setPseudonymPatientId(pseudoPatientId_2); pseudonymMap_2.setPseudonymPatientIdAssigningAuthority(pseudoAuthorityId_2); pseudonymMap_2.setRealPatientId(realPatientId_2); pseudonymMap_2.setRealPatientIdAssigningAuthority(realAuthorityId_2); // create third test PseudonymMap - Ids are different pseudonymMap_3 = new PseudonymMap(); pseudonymMap_3.setPseudonymPatientId(pseudoPatientId_3); pseudonymMap_3.setPseudonymPatientIdAssigningAuthority(pseudoAuthorityId_3); pseudonymMap_3.setRealPatientId(realPatientId_3); pseudonymMap_3.setRealPatientIdAssigningAuthority(realAuthorityId_3); // initialize contents of internal memory PseudonymMapManager.readMap(); }
// This code worked successfully on command-line but never as JUnit test // <script>:1: undefined method `+' for nil:NilClass (NoMethodError) // raised at "Object obj1 = engine1.eval("$Value + 2010.to_s");" // @Test public void testMultipleEngineStates() throws ScriptException { logger1.info("Multiple Engine States"); ScriptEngine engine1; ScriptEngine engine2; synchronized (this) { System.setProperty("org.jruby.embed.localcontext.scope", "singlethread"); System.setProperty("org.jruby.embed.localvariable.behavior", "global"); ScriptEngineManager manager = new ScriptEngineManager(); List<ScriptEngineFactory> factories = manager.getEngineFactories(); ScriptEngineFactory factory = null; while (factories.iterator().hasNext()) { factory = factories.iterator().next(); if ("ruby".equals(factory.getLanguageName())) { break; } } engine1 = factory.getScriptEngine(); engine2 = factory.getScriptEngine(); } engine1.put("Value", "value of the first engine"); engine2.put("Value", new Double(-0.0149)); Object obj1 = engine1.eval("$Value + 2010.to_s"); Object obj2 = engine2.eval("$Value + 2010"); assertNotSame(obj1, obj2); engine1 = null; engine2 = null; }
// @Test public void graphBubbleSort() { System.out.println("size, time"); for (int i = 0; i < 255; i++) { int size = Sort.randBoundInt(r, 100, 10000); Random pop = new Random(42); ArrayList<Integer> arr = new ArrayList<Integer>(size); for (int j = 0; j < size; j++) { arr.add(pop.nextInt()); } Integer[] a = arr.toArray(new Integer[0]); long startTime = System.nanoTime(); Sort.<Integer>bubblesort(a); long stopTime = System.nanoTime(); long elapsedTime = stopTime - startTime; System.out.println(size + ", " + elapsedTime); } }
@Test public void testReadProductNodes() { Date startDate = Calendar.getInstance().getTime(); Product product = new Product("name", "desc", 100, 100); File file = TestUtil.getTestFile( productsFolder + "SP04_HRI1_X__1O_20050605T090007_20050605T090016_DLR_70_PREU.BIL.ZIP"); System.setProperty("snap.dataio.reader.tileWidth", "100"); System.setProperty("snap.dataio.reader.tileHeight", "100"); try { Product finalProduct = reader.readProductNodes(file, null); assertEquals(4, finalProduct.getBands().length); assertEquals("WGS84(DD)", finalProduct.getSceneGeoCoding().getGeoCRS().getName().toString()); assertEquals("SPOTView", finalProduct.getProductType()); assertEquals(0, finalProduct.getMaskGroup().getNodeCount()); assertEquals(2713, finalProduct.getSceneRasterWidth()); assertEquals(2568, finalProduct.getSceneRasterHeight()); Date endDate = Calendar.getInstance().getTime(); assertTrue( "The load time for the product is too big!", (endDate.getTime() - startDate.getTime()) / (60 * 1000) < 30); } catch (IOException e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } }
@Test public void testAddPerformance() { boolean enabled = false; if (enabled) { byte[] one = new byte[] { 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41 }; // Random value int ITERATIONS = 10000000; long now1 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { DataWord x = new DataWord(one); x.add(x); } System.out.println("Add1: " + (System.currentTimeMillis() - now1) + "ms"); long now2 = System.currentTimeMillis(); for (int i = 0; i < ITERATIONS; i++) { DataWord x = new DataWord(one); x.add2(x); } System.out.println("Add2: " + (System.currentTimeMillis() - now2) + "ms"); } else { System.out.println("ADD performance test is disabled."); } }
/** Test of paintComponent method, of class GraphPanelChart. */ @Test public void testPaintComponent() { System.out.println("paintComponent"); Graphics g = new TestGraphics(); GraphPanelChart instance = new GraphPanelChart(); instance.setSize(500, 500); instance.getChartSettings().setDrawFinalZeroingLines(true); instance.getChartSettings().setDrawCurrentX(true); instance.getChartSettings().setExpendRows(true); final ConcurrentSkipListMap<String, AbstractGraphRow> rows = new ConcurrentSkipListMap<String, AbstractGraphRow>(); instance.setRows(rows); final GraphRowAverages row1 = new GraphRowAverages(); row1.setDrawThickLines(true); row1.setDrawLine(true); row1.setDrawBar(true); row1.setDrawValueLabel(true); row1.setMarkerSize(AbstractGraphRow.MARKER_SIZE_BIG); rows.put("test 1", row1); row1.add(System.currentTimeMillis(), 20); instance.paintComponent(g); row1.add(System.currentTimeMillis(), 540); instance.setxAxisLabelRenderer(new DateTimeRenderer("HH:mm:ss")); instance.paintComponent(g); row1.add(System.currentTimeMillis(), 8530); instance.paintComponent(g); }
@Test @SuppressWarnings("unchecked") public void testDoWithRetry_ReadTimeOut() throws Exception { AmazonElasticMapReduceCustomClient client = new AmazonElasticMapReduceCustomClient("dummy", "dummy"); client.setRequestInterval(100); Callable callable = mock(Callable.class); AmazonClientException exception = new AmazonClientException("Unable to execute HTTP request: Read timed out"); when(callable.call()).thenThrow(exception, exception, exception).thenReturn(new Object()); long startTime = System.currentTimeMillis(); Object result = client.doThrottleSafe(callable); assertNotNull(result); assertThat( (System.currentTimeMillis() - startTime), greaterThanOrEqualTo(3 * client.getRequestInterval())); // now exceed retries client.setMaxRetriesOnConnectionErrors(2); when(callable.call()).thenThrow(exception, exception, exception).thenReturn(new Object()); try { client.doThrottleSafe(callable); fail("should throw exception"); } catch (Exception e) { assertSame(exception, e); } }
@Test public void testAgentStatMonitor() throws InterruptedException { // Given final long collectionIntervalMs = 1000 * 1; final int numCollectionsPerBatch = 2; final int minNumBatchToTest = 2; final long totalTestDurationMs = collectionIntervalMs + collectionIntervalMs * numCollectionsPerBatch * minNumBatchToTest; // When System.setProperty("pinpoint.log", "test."); AgentStatCollectorFactory agentStatCollectorFactory = new AgentStatCollectorFactory(new TestableTransactionCounter()); AgentStatMonitor monitor = new AgentStatMonitor( this.dataSender, "agentId", System.currentTimeMillis(), agentStatCollectorFactory, collectionIntervalMs, numCollectionsPerBatch); monitor.start(); Thread.sleep(totalTestDurationMs); monitor.stop(); // Then assertTrue(tBaseRecorder.size() >= minNumBatchToTest); for (TAgentStatBatch agentStatBatch : tBaseRecorder) { logger.debug("agentStatBatch:{}", agentStatBatch); assertTrue(agentStatBatch.getAgentStats().size() <= numCollectionsPerBatch); } }
@Test public void testUpsertDateValues() throws Exception { long ts = nextTimestamp(); Date now = new Date(System.currentTimeMillis()); ensureTableCreated(getUrl(), TestUtil.PTSDB_NAME, null, ts - 2); Properties props = new Properties(); props.setProperty( PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1)); // Execute at timestamp 1 Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String dateString = "1999-01-01 02:00:00"; PreparedStatement upsertStmt = conn.prepareStatement( "upsert into ptsdb(inst,host,date) values('aaa','bbb',to_date('" + dateString + "'))"); int rowsInserted = upsertStmt.executeUpdate(); assertEquals(1, rowsInserted); upsertStmt = conn.prepareStatement( "upsert into ptsdb(inst,host,date) values('ccc','ddd',current_date())"); rowsInserted = upsertStmt.executeUpdate(); assertEquals(1, rowsInserted); conn.commit(); props.setProperty( PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 1 conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String select = "SELECT date,current_date() FROM ptsdb"; ResultSet rs = conn.createStatement().executeQuery(select); Date then = new Date(System.currentTimeMillis()); assertTrue(rs.next()); Date date = DateUtil.parseDate(dateString); assertEquals(date, rs.getDate(1)); assertTrue(rs.next()); assertTrue(rs.getDate(1).after(now) && rs.getDate(1).before(then)); assertFalse(rs.next()); }
@Test public void testSendAndReceive() throws Exception { // Run the main controller ControllerRunner controllerRunner = new ControllerRunner(10, 9090, InetAddress.getLocalHost(), "127.0.0.1", 8008); controllerRunner.run(); System.out.println("Controller running"); Random random = new Random(); int player = random.nextInt(); // Connect a new controller and send test alarm Controller controller = new Controller(10); Socket connection1 = controller.connectTo(InetAddress.getLocalHost().getHostAddress(), 9090); Alarm alarm = new Alarm(player, System.currentTimeMillis(), new PlayerCause(player)); controller.send(alarm, connection1); Controller controller2 = new Controller(10); Socket connection2 = controller2.connectTo(InetAddress.getLocalHost().getHostAddress(), 9090); long alarmtime = System.currentTimeMillis() + 500; Position position1 = new Position(player, System.currentTimeMillis(), 1, 2, 3); Position position2 = new Position(player, alarmtime, 100, 200, 300); controller2.send(position1, connection2); controller2.send(position2, connection2); controller2.send(new Request(player, DataType.ACCEL, -1, -1), connection2); controller2.send(new Request(player, DataType.POS, -1, -1), connection2); Thread.sleep(15000); List<Sendable> received = controller2.receive(connection2); List<Alarm> alarms = new ArrayList<Alarm>(); List<Acceleration> accelerations = new ArrayList<Acceleration>(); List<Position> positions = new ArrayList<Position>(); // Distribute the sendable objects for (Sendable sendable : received) { if (sendable instanceof Alarm) { alarms.add((Alarm) sendable); } else if (sendable instanceof Service) { Service service = (Service) sendable; List<?> data = service.getData(); for (Object o : data) { if (o instanceof Acceleration) { accelerations.add((Acceleration) o); } else if (o instanceof Position) { positions.add((Position) o); } } } } controller.disconnectFromClient(connection1); controller2.disconnectFromClient(connection2); assertTrue("Alarm was not sent from controller", alarms.size() >= 1); assertTrue("Acceleration not received from controller", accelerations.size() >= 1); assertTrue("Position 1 not contained in received positions", positions.contains(position1)); assertTrue("Position 2 not contained in received positions", positions.contains(position2)); }
/** * checkEnvのテストケース 異常系:"ASAKUSA_HOME"の設定が不正のケース * * @throws Exception */ @Test public void checkEnvTest04() throws Exception { ConfigurationLoader.init(properties_db, true, false); Map<String, String> m = new HashMap<String, String>(); m.put(Constants.ASAKUSA_HOME, "J:\temp"); m.put( Constants.THUNDER_GATE_HOME, ConfigurationLoader.getEnvProperty(Constants.THUNDER_GATE_HOME)); ConfigurationLoader.setEnv(m); Properties p = System.getProperties(); p.setProperty(Constants.ASAKUSA_HOME, "J:\temp"); p.setProperty(Constants.THUNDER_GATE_HOME, "src/test"); ConfigurationLoader.setSysProp(p); System.setProperties(p); try { ConfigurationLoader.checkEnv(); fail(); } catch (Exception e) { assertTrue(e instanceof Exception); System.out.println(e.getMessage()); e.printStackTrace(); } }
@Test public void sleeps() throws InterruptedException { long start = System.currentTimeMillis(); Thread.sleep(100); long duration = System.currentTimeMillis() - start; assertTrue("Thread.sleed did not wait enogh", duration >= 100); }
public void execute(WorkerProcessContext workerProcessContext) { // Check environment assertThat(System.getProperty("test.system.property"), equalTo("value")); assertThat(System.getenv().get("TEST_ENV_VAR"), equalTo("value")); // Check ClassLoaders ClassLoader antClassLoader = Project.class.getClassLoader(); ClassLoader thisClassLoader = getClass().getClassLoader(); ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader(); assertThat(antClassLoader, not(sameInstance(systemClassLoader))); assertThat(thisClassLoader, not(sameInstance(systemClassLoader))); assertThat(antClassLoader.getParent(), equalTo(systemClassLoader.getParent())); try { assertThat( thisClassLoader.loadClass(Project.class.getName()), sameInstance((Object) Project.class)); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } // Send some messages TestListenerInterface sender = workerProcessContext.getServerConnection().addOutgoing(TestListenerInterface.class); sender.send("message 1", 1); sender.send("message 2", 2); }
/** HG: measures time needed to check a pair of huge random graphs */ @Test public void testHugeGraph() { int n = 700; long time = System.currentTimeMillis(); DirectedGraph<Integer, DefaultEdge> g1 = SubgraphIsomorphismTestUtils.randomGraph(n, n * n / 50, 12345), g2 = SubgraphIsomorphismTestUtils.randomSubgraph(g1, n / 2, 54321); VF2SubgraphIsomorphismInspector<Integer, DefaultEdge> vf2 = new VF2SubgraphIsomorphismInspector<>(g1, g2); assertEquals(true, vf2.isomorphismExists()); SubgraphIsomorphismTestUtils.showLog( "|V1| = " + g1.vertexSet().size() + ", |E1| = " + g1.edgeSet().size() + ", |V2| = " + g2.vertexSet().size() + ", |E2| = " + g2.edgeSet().size() + " - " + (System.currentTimeMillis() - time) + "ms"); }
@Ignore @Test(timeout = 5 * 60 * 1000) public final void testDeJong_big() { final int dim = 40; final double bound = 100; long start = System.currentTimeMillis(); FunctionNEW f = new Function_DeJong_nD(dim); System.out.println(System.currentTimeMillis() - start); /* * 20 40 80 160 * 600 2500 8000 65000 */ Box area = new Box(dim, new RealInterval(-bound, bound)); solver = new SteepestDescent(f, area); start = System.currentTimeMillis(); double res = solver.localMinimum(area); System.out.println(System.currentTimeMillis() - start); assertTrue(res < 1e-4); // start from 0 area = new Box(dim, new RealInterval(-bound - bound / 2.0, bound - bound / 5.0)); res = solver.localMinimum(area); assertTrue(res < 1); area = new Box(dim, new RealInterval(-10, -9)); // bad point... res = solver.localMinimum(area); assertTrue(res < 1); }
@Test public void testStartServlet() throws Exception { String old = System.getProperty("karaf.data"); System.setProperty("karaf.data", new File("target").getCanonicalPath()); try { MavenDownloadProxyServlet servlet = new MavenDownloadProxyServlet( runtimeProperties, System.getProperty("java.io.tmpdir"), null, false, null, null, null, null, 0, null, null, null, projectDeployer, 5); servlet.start(); } finally { if (old != null) { System.setProperty("karaf.data", old); } } }
protected boolean execute(int address, String expectedOutput) { boolean isSuccess = false; Cpu cpu = computer.getCpu(); cpu.writeRegister(false, Cpu.PC, address); long startTime = System.currentTimeMillis(); while ((System.currentTimeMillis() - startTime) < MAX_EXECUTION_TIME || terminal.getWrittenData().length() > Terminal.MAX_DATA_LENGTH) { try { cpu.executeNextOperation(); if (cpu.isHaltMode()) { throw new IllegalStateException("HALT mode"); } } catch (Exception e) { e.printStackTrace(); fail( "can't execute operation, PC: 0" + Integer.toOctalString(cpu.readRegister(false, Cpu.PC))); } if (expectedOutput.equals(terminal.getWrittenData())) { isSuccess = true; break; } } return isSuccess; }
private File getTestTempFile(String prefix, String suffix) throws IOException { String tmpPath = System.getProperty("java.io.tmpdir", "/tmp"); String user = System.getProperty("user.name", "unknown-user"); File dir = new File(tmpPath + "/" + user); dir.mkdirs(); return File.createTempFile(prefix, suffix, dir); }
@Test public void executionStressTest() { long startTime = System.currentTimeMillis(); String s; for (int i = 0; i < 10000; i++) { s = cross.prettifyNumber(1_000_000L); assertEquals("1M", s); s = cross.prettifyNumber(585L); assertEquals("585", s); s = cross.prettifyNumber((long) 2_500_000.34D); assertEquals("2.5M", s); s = cross.prettifyNumber(1_123_456_789L); assertEquals("1.1B", s); s = cross.prettifyNumber(3_500_000_000_000L); assertEquals("3.5T", s); s = cross.prettifyNumber(0L); assertEquals("0", s); s = cross.prettifyNumber(4_000_000_000_000_000L); assertEquals("4Q", s); } long stopTime = System.currentTimeMillis(); long elapsedTime = stopTime - startTime; System.out.println(elapsedTime + " ---> StringApproach execution time wtih a 10000 loop"); }
@Test public void test_performance1() throws MatlabOutputException { String matlab_function = "return_cell_array_different_size"; long tic = System.currentTimeMillis(); int numout = 2; Object[] argsT = new Object[1]; argsT[0] = 1; Object[] output = null; try { output = matlabClient.executeFeval(matlab_function, argsT, numout); } catch (MatlabRMIException e) { fail("Exception occurred: " + e.getMessage()); } if (output == null || output[0] == null) { fail("Unexpected error occurred"); } long toc = System.currentTimeMillis(); long elapsed_time_long = toc - tic; double elapsed_time = (double) elapsed_time_long / 1000.0; Object[] result = (Object[]) output[0]; double matlab_elapsed_time = ((double[]) output[1])[0]; System.out.println( String.format( "Elapsed_time = %s Matlab_elapsed_time = %s", elapsed_time, matlab_elapsed_time)); assertTrue(result.length == 10); assertTrue(elapsed_time < matlab_elapsed_time); }
@Test public void testGetProductComponentsOnFileInput() { File file = TestUtil.getTestFile( productsFolder + "SP04_HRI1_X__1O_20050605T090007_20050605T090016_DLR_70_PREU.BIL/metadata.xml"); System.setProperty("snap.dataio.reader.tileWidth", "100"); System.setProperty("snap.dataio.reader.tileHeight", "100"); try { reader.readProductNodes(file, null); TreeNode<File> components = reader.getProductComponents(); assertEquals(3, components.getChildren().length); String[] expectedIds = new String[] {"metadata.dim", "metadata.xml", "geolayer.bil"}; int componentsAsExpected = 0; for (TreeNode<File> component : components.getChildren()) { for (String expectedValue : expectedIds) { if (component.getId().toLowerCase().equals(expectedValue.toLowerCase())) { componentsAsExpected++; } } } assertEquals(3, componentsAsExpected); } catch (IOException e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } }
@Test @Ignore public void shouldFindAllByIdQuery() { // todo : find solution for findAll(Iterable<Ids> ids) // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); sampleEntity.setId(documentId); sampleEntity.setMessage("hello world."); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity); String documentId2 = randomNumeric(5); SampleEntity sampleEntity2 = new SampleEntity(); sampleEntity2.setId(documentId2); sampleEntity2.setMessage("hello world."); sampleEntity2.setVersion(System.currentTimeMillis()); repository.save(sampleEntity2); // when Iterable<SampleEntity> sampleEntities = repository.findAll(Arrays.asList(documentId, documentId2)); // then assertNotNull("sample entities cant be null..", sampleEntities); }
@Test public void testWritable() throws IOException { assertTrue(true); Settings settings = SettingsBuilder.createDefault().build(); assertNotNull(settings.getString("foo")); assertEquals("bar", settings.getString("foo")); assertNotNull(settings.getString("os.name")); assertEquals(System.getProperty("os.name"), settings.getString("os.name")); WritableSettings w = new WritableSettings("whoo", settings); w.setString("wow", "its writable"); assertNotNull(w.getString("wow")); assertEquals("its writable", w.getString("wow")); assertEquals("x", w.getString("wubbity", "x")); assertEquals(23, w.getInt("age", -1)); assertEquals(23L, w.getLong("age", -1L)); assertNull(settings.getString("wow")); assertEquals(System.getProperty("os.name"), w.getString("os.name")); w.setString("os.name", "BeOS"); assertEquals("BeOS", w.getString("os.name")); w.clear("os.name"); assertNull(w.getString("os.name")); w.setString("os.name", "OS/2"); assertEquals("OS/2", w.getString("os.name")); }
@Test public void testClearVariables() throws ScriptException { logger1.info("Clear Variables Test"); ScriptEngine instance = null; synchronized (this) { System.setProperty("org.jruby.embed.localcontext.scope", "singlethread"); System.setProperty("org.jruby.embed.localvariable.behavior", "global"); ScriptEngineManager manager = new ScriptEngineManager(); instance = manager.getEngineByName("jruby"); } instance.put("gvar", ":Gvar"); String result = (String) instance.eval("$gvar"); assertEquals(":Gvar", result); instance.getBindings(ScriptContext.ENGINE_SCOPE).remove("gvar"); instance .getContext() .setAttribute("org.jruby.embed.clear.variables", true, ScriptContext.ENGINE_SCOPE); instance.eval(""); instance .getContext() .setAttribute("org.jruby.embed.clear.variables", false, ScriptContext.ENGINE_SCOPE); result = (String) instance.eval("$gvar"); assertNull(result); instance = null; }
@Before public void dbInit() throws Exception { String configFileName = System.getProperty("user.home"); if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) { configFileName += "/.pokerth/config.xml"; } else { configFileName += "/AppData/Roaming/pokerth/config.xml"; } File file = new File(configFileName); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); doc.getDocumentElement().normalize(); Element configNode = (Element) doc.getElementsByTagName("Configuration").item(0); Element dbAddressNode = (Element) configNode.getElementsByTagName("DBServerAddress").item(0); String dbAddress = dbAddressNode.getAttribute("value"); Element dbUserNode = (Element) configNode.getElementsByTagName("DBServerUser").item(0); String dbUser = dbUserNode.getAttribute("value"); Element dbPasswordNode = (Element) configNode.getElementsByTagName("DBServerPassword").item(0); String dbPassword = dbPasswordNode.getAttribute("value"); Element dbNameNode = (Element) configNode.getElementsByTagName("DBServerDatabaseName").item(0); String dbName = dbNameNode.getAttribute("value"); final String dbUrl = "jdbc:mysql://" + dbAddress + ":3306/" + dbName; Class.forName("com.mysql.jdbc.Driver").newInstance(); dbConn = DriverManager.getConnection(dbUrl, dbUser, dbPassword); }
/* DATAES-82 */ @Test public void shouldFindAllByIdQuery() { // given String documentId = randomNumeric(5); SampleEntity sampleEntity = new SampleEntity(); sampleEntity.setId(documentId); sampleEntity.setMessage("hello world."); sampleEntity.setVersion(System.currentTimeMillis()); repository.save(sampleEntity); String documentId2 = randomNumeric(5); SampleEntity sampleEntity2 = new SampleEntity(); sampleEntity2.setId(documentId2); sampleEntity2.setMessage("hello world."); sampleEntity2.setVersion(System.currentTimeMillis()); repository.save(sampleEntity2); // when Iterable<SampleEntity> sampleEntities = repository.findAll(Arrays.asList(documentId, documentId2)); // then assertNotNull("sample entities cant be null..", sampleEntities); List<SampleEntity> entities = Lists.newArrayList(sampleEntities); assertThat(entities.size(), is(2)); }
@Test public void serializeStringAsAsciiBytes() throws Exception { final String data = "abc123"; final Charset asciiCharset = Charset.forName("US-ASCII"); final int loops = 1000; ByteArrayOutputStream out = new ByteArrayOutputStream(10); byte[] expecteds = new byte[] {'a', 'b', 'c', '1', '2', '3'}; long start = 0; start = System.nanoTime(); for (int i = 0; i < loops; i++) { AsciiUtils.writeStringAsAsciiBytes(data, out); out.flush(); assertArrayEquals(expecteds, out.toByteArray()); out.reset(); } System.out.println( "AsciiUtils#writeStringAsAsciiBytes() elapsed time: " + ((System.nanoTime() - start) / 1000000) + " ms"); start = System.nanoTime(); for (int i = 0; i < loops; i++) { out.write(data.getBytes(asciiCharset)); out.flush(); assertArrayEquals(expecteds, out.toByteArray()); out.reset(); } System.out.println( "String#getBytes() elapsed time: " + ((System.nanoTime() - start) / 1000000) + " ms"); }
/** Test of getInterface method, of class Jsr223JRubyEngine. */ @Test public void testGetInterface_Object_Class() throws FileNotFoundException, ScriptException { logger1.info("getInterface (with receiver)"); ScriptEngine instance; synchronized (this) { System.setProperty("org.jruby.embed.localcontext.scope", "singlethread"); System.setProperty("org.jruby.embed.localvariable.behavior", "transient"); ScriptEngineManager manager = new ScriptEngineManager(); instance = manager.getEngineByName("jruby"); } String filename = basedir + "/src/test/ruby/org/jruby/embed/ruby/position_function.rb"; Reader reader = new FileReader(filename); Bindings bindings = instance.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("initial_velocity", 30.0); bindings.put("initial_height", 30.0); bindings.put("system", "metric"); Object receiver = instance.eval(reader, bindings); Class returnType = PositionFunction.class; PositionFunction result = (PositionFunction) ((Invocable) instance).getInterface(receiver, returnType); double expResult = 75.9; double t = 3.0; assertEquals(expResult, result.getPosition(t), 0.1); expResult = 20.2; t = 1.0; assertEquals(expResult, result.getVelocity(t), 0.1); instance.getBindings(ScriptContext.ENGINE_SCOPE).clear(); instance = null; }