src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking) { this.privateNetworking = privateNetworking; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptio... | @Test public void testPrivateNetworking() { TemplateOptions options = new DigitalOcean2TemplateOptions().privateNetworking(true); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getPrivateNetworking(), true); } |
Car { private Car() { if (servoCommand == null) { Environment env = Config.getEnvironment(); String servo_CommandConfig="servoblaster"; try { servo_CommandConfig = env.getString(Config.SERVO_COMMAND); } catch (Exception e) { ErrorHandler.getInstance().handle(e); } switch (servo_CommandConfig) { case "adafruit": try { s... | @Test public void testCar() throws Exception { Car car = getCar(); car.setPowerOn(); int tvalues[]= {-1,120,1000}; for (int tvalue:tvalues) { car.turn(new ServoPosition(tvalue,tvalue*10)); } int dvalues[]= {-1,150,1000}; for (int dvalue:dvalues) { car.drive(new ServoPosition(dvalue,dvalue*10)); } if (debug) servoComman... |
Configuration { public Configuration(String graphFilePath, boolean readInis) { this.graphFilePath = graphFilePath; setGraph(TinkerGraph.open()); File graphFile = getGraphFile(); if (readInis) { fromIni(); write(); } else { if (graphFile.exists()) { read(graphFile); } } } Configuration(String graphFilePath, boolean read... | @Test public void testConfiguration() throws Exception { Configuration config=getMockConfiguration(); long nodeCount = config.g().V().count().next().longValue(); assertEquals(1,nodeCount); config.write(); assertTrue(config.getGraphFile().canRead()); config.getGraphFile().delete(); } |
Environment { private Environment() { runningOnRaspberryPi = isPi(); } private Environment(); Environment(String propFilePath); static String readFirstLine(File file); static String osRelease(); boolean isPi(); static Environment getInstance(); boolean runningOnRaspberryPi(); Properties getProperties(); JsonObject as... | @Test public void testEnvironment() throws Exception { String ip = "1.2.3.4"; int port = 8080; File propFile = setProperties(Config.REMOTECAR_HOST, ip, Config.WEBCONTROL_PORT, "" + port); Environment env = Config.getEnvironment(); String piIp = env.getString(Config.REMOTECAR_HOST); assertEquals(ip, piIp); assertFalse(e... |
Environment { public List<String> getMyIpAddresses() { try { return Collections.list(NetworkInterface.getNetworkInterfaces()).stream() .map(iface -> Collections.list(iface.getInetAddresses())) .flatMap(Collection::stream).map(InetAddress::getHostAddress) .collect(Collectors.toList()); } catch (SocketException e) { LOG.... | @Test public void testGetMyIpAddresses() { List<String> ips = Environment.getInstance().getMyIpAddresses(); assertNotNull(ips); assertTrue(ips.size() > 1); } |
Environment { public static void mock() { Environment.from("../rc-drivecontrol/src/test/resources/dukes/dukes.ini"); } private Environment(); Environment(String propFilePath); static String readFirstLine(File file); static String osRelease(); boolean isPi(); static Environment getInstance(); boolean runningOnRaspberr... | @Test public void testMock() throws Exception { Environment.mock(); JsonObject jo = Environment.getInstance().asJsonObject(); String json = jo.toString(); if (debug) System.out.println(json); Environment env = Config.getEnvironment(); assertEquals(-20.0,env.getDouble(Config.WHEEL_MAX_LEFT_ANGLE),0.001); } |
ClusterStarter { public void deployVerticles(AbstractVerticle... verticles) throws Exception { DeploymentOptions deploymentOptions = this.getDeployMentOptions(true); if (vertx == null) { this.clusteredVertx(resultHandler -> { vertx = resultHandler.result(); if (vertx == null) { ErrorHandler.getInstance().handle(new Run... | @Test public void testClusterStarter() throws Exception { Environment.mock(); ClusterStarter starter = new ClusterStarter(); TestVerticle testVerticle = new TestVerticle(); starter.deployVerticles(testVerticle); testVerticle.waitStatus(Status.started, ClusterStarter.MAX_START_TIME, 10); int minLoops=5; while (testVerti... |
ErrorHandler { public static String getStackTraceText(Throwable th) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); th.printStackTrace(pw); String exceptionText = sw.toString(); return exceptionText; } static String getStackTraceText(Throwable th); } | @Test public void testErrorHandler() { String trace=null; try { throw new Exception("oops - a problem"); } catch (Throwable th) { trace=ErrorHandler.getStackTraceText(th); } assertNotNull(trace); assertTrue(trace.contains("oops - a problem")); assertTrue(trace.contains("TestErrorHandler.java:18")); } |
ROI { public ROI(String name,double rx, double ry, double rw, double rh) { this.name=name; this.rx = rx; this.ry = ry; this.rw = rw; this.rh = rh; } ROI(String name,double rx, double ry, double rw, double rh); Rect roiRect(Size base); Mat region(Mat image); String toString(); } | @Test public void testROI() throws Exception { if (!isTravis()) { NativeLibrary.load(); File imgRoot = new File(testPath); assertTrue(imgRoot.isDirectory()); Mat image = Imgcodecs.imread(testPath + "dukes_roi_test_image.jpg"); assertNotNull(image); assertEquals(960, image.height()); assertEquals(1280, image.width()); R... |
StraightLaneNavigator extends TinkerPopDatabase implements Navigator { public StraightLaneNavigator() { this(DEFAULT_TIME_WINDOW); } StraightLaneNavigator(); StraightLaneNavigator(int timeWindow); DukesVerticle getSender(); void setSender(DukesVerticle sender); Vertex addToGraph(LaneDetectionResult ldr); @Override Lan... | @Test public void testStraightLaneNavigator() { LaneDetectionResult ldrs[] = { getLdr(1, 0, -45., 0., 45.), getLdr(2, 100, -46., 1., 46.), getLdr(3, 200, -47., 0., 47.) }; StraightLaneNavigator nav = new StraightLaneNavigator(); for (LaneDetectionResult ldr : ldrs) nav.getNavigationInstruction(ldr); long nodeCount = na... |
StraightLaneNavigator extends TinkerPopDatabase implements Navigator { @Override public JsonObject getNavigationInstruction(LaneDetectionResult ldr) { JsonObject message = null; if (this.emergencyStopActivated) return message; setTime(ldr); Vertex ldrVertex=addToGraph(ldr); boolean showDebug = true; analyzeAngleRanges(... | @Test public void testFromVideo() throws Exception { NativeLibrary.load(); Navigator nav = new StraightLaneNavigator(); String testUrl = "http: ImageFetcher imageFetcher = new ImageFetcher(testUrl); imageFetcher.open(); int frameIndex = 0; int maxFrameIndex = 300; while (frameIndex < maxFrameIndex && imageFetcher.hasNe... |
WatchDog extends DukesVerticle { public WatchDog(Car car) throws Exception { super(Characters.FLASH); this.car = car; Environment env = Config.getEnvironment(); HEARTBEAT_INTERVAL_MS=env.getInteger(Config.WATCHDOG_HEARTBEAT_INTERVAL_MS); MAX_MISSED_BEATS=env.getInteger(Config.WATCHDOG_MAX_MISSED_BEATS); } WatchDog(Car ... | @Test public void testWatchDog() throws Exception { ClusterStarter clusterStarter=new ClusterStarter(); Car car=TestCar.getCar(); Environment env = Config.getEnvironment(); int heartBeatInterval=env.getInteger(Config.WATCHDOG_HEARTBEAT_INTERVAL_MS); assertEquals(20,heartBeatInterval); int maxMissedBeats=env.getInteger(... |
Car { public Steering getSteering() { return steering; } private Car(); void configure(Engine engine, Steering steering, Led led); void setPowerOn(); void setPowerOff(); boolean powerIsOn(); void stop(); void turn(ServoPosition position); void drive(ServoPosition speed); Engine getEngine(); Steering getSteering(); Led... | @Test public void testSteering() throws Exception { Car car = getCar(); Steering steering = car.getSteering(); steering.center(); ServoPosition cpos = steering.getSteeringMap().getCurrentPosition(); System.out.println(cpos); } |
Car { public Led getLed() { return led; } private Car(); void configure(Engine engine, Steering steering, Led led); void setPowerOn(); void setPowerOff(); boolean powerIsOn(); void stop(); void turn(ServoPosition position); void drive(ServoPosition speed); Engine getEngine(); Steering getSteering(); Led getLed(); stat... | @Test public void testLed() throws Exception { Car car = getCar(); Led led = car.getLed(); led.statusLedOn(); led.statusLedOff(); if (debug) servoCommand.showLog(); } |
ImageFetcher { public ImageFetcher(String source) { this.source = source; } ImageFetcher(String source); double getFps(); void setFps(double fps); int getFrameIndex(); boolean isStaticImage(); void setStaticImage(boolean staticImage); boolean open(); void close(); long waitForNextFrame(); Image fetch(); Image createNex... | @Test public void testImageFetcher() { ImageFetcher imageFetcher = getTestImageFetcher(); imageFetcher.debug=debug; Image image; do { image= imageFetcher.fetch(); } while (image != null); if (debug) { String msg = String.format("%s has %d frames", testSource, imageFetcher.getFrameIndex()); System.out.println(msg); } as... |
ImageFetcher { public Observable<Image> toObservable() { Observable<Image> observable = Observable .create(new ObservableOnSubscribe<Image>() { @Override public void subscribe(ObservableEmitter<Image> observableEmitter) throws Exception { hasNext=true; while (hasNext && !isClosed()) { final Image image = ImageFetcher.t... | @Test public void testImageFetcherObservable() { ImageFetcher imageFetcher = getTestImageFetcher(); Observable<Image> imageObservable = imageFetcher.toObservable(); ImageObserver imageObserver = new ImageObserver(); imageObserver.debug=debug; imageObservable.subscribe(imageObserver); assertNull(imageObserver.error); as... |
RemoteCar extends DukesVerticle { public RemoteCar() { super(Characters.GENERAL_LEE); } RemoteCar(); @Override void start(); void parseArguments(String[] args); void mainInstance(String... args); static void main(String... args); @Option(name = "-ph", aliases = { "--publichost" }, usage = "hostname") String publicHost;... | @Test public void testRemoteCar() throws Exception { Environment.mock(); ClusterStarter clusterStarter = new ClusterStarter(); clusterStarter.prepare(); RemoteCar remoteCar = new RemoteCar(); clusterStarter.deployVerticles(remoteCar); DukesVerticle.debug=true; remoteCar.waitStatus(Status.started, ClusterStarter.MAX_STA... |
RemoteCar extends DukesVerticle { public static void main(String... args) { RemoteCar remoteCar = new RemoteCar(); remoteCar.mainInstance(args); } RemoteCar(); @Override void start(); void parseArguments(String[] args); void mainInstance(String... args); static void main(String... args); @Option(name = "-ph", aliases =... | @Test public void testRemoteCarCommandLine() { Environment.mock(); String args[]= {}; RemoteCar.main(args); } |
PerspectiveShift implements UnaryOperator<Mat> { @Override public Mat apply(Mat srcImage) { Mat destImage = new Mat(); Imgproc.warpPerspective(srcImage, destImage, perspectiveTransform, srcImage.size()); return destImage; } PerspectiveShift(Polygon imagePolygon, Polygon worldPolygon); @Override Mat apply(Mat srcImage);... | @Test public void testChessboard() { CameraMatrix matrix = new CameraMatrix(7, 7); Mat chessboard = Imgcodecs.imread(testPath + "dukes_chessBoard008.png"); Point[] corners = matrix.findOuterChessBoardCornerPoints(chessboard); assertNotNull(corners); assertEquals(4, corners.length); if (debug) { System.out.print("corner... |
RSAKeyPair { public static RSAKeyPair fromExponents(byte[] e, byte[] p, byte[] q) { final BigInteger eInt = BigIntegers.fromUnsignedByteArray(e), pInt = BigIntegers.fromUnsignedByteArray(p), qInt = BigIntegers.fromUnsignedByteArray(q), nInt = pInt.multiply(qInt), mInt = pInt.subtract(BigInteger.ONE).multiply(qInt.subtr... | @Test public void fromExponents() throws Exception { RSAKeyPair rsaPair = RSAKeyPair.fromExponents(rsaSpec.e, rsaSpec.p, rsaSpec.q); assertArrayEquals(rsaPair.n, rsaSpec.n); assertArrayEquals(rsaPair.e, rsaSpec.e); assertArrayEquals(rsaPair.d, rsaSpec.d); assertArrayEquals(rsaPair.p, rsaSpec.p); assertArrayEquals(rsaPa... |
Main { public void shutdown() { try { if (hookThread != null) Runtime.getRuntime().removeShutdownHook(hookThread); ledger.close(); log("shutting down"); network.shutdown(); clientHTTPServer.shutdown(); } catch (Exception e) { } synchronized (parser) { parser.notifyAll(); } try { logger.close(); } catch (Exception e) { ... | @Test public void checkLimitRequestsForKey() throws Exception { PrivateKey myKey = TestKeys.privateKey(3); List<Main> mm = new ArrayList<>(); for (int i = 0; i < 4; i++) mm.add(createMain("node" + (i + 1), false)); mm.forEach(x -> x.config.setIsFreeRegistrationsAllowedFromYaml(true)); Main main = mm.get(0); Client clie... |
RSAOAEPPublicKey extends AbstractPublicKey { @NonNull @Override public boolean checkSignature(InputStream input, byte[] signature, HashType hashType, int saltLength) throws IllegalStateException, IOException { if (state == null) { throw new IllegalStateException(); } else { final Digest primaryDigest = hashType.makeDig... | @Test public void checkSignature() throws Exception { AbstractPublicKey rsaPublicKey = pssSpec.getPublicKey(); AbstractPrivateKey rsaPrivateKey = pssSpec.getPrivateKey(); assertArrayEquals( rsaPrivateKey.sign(pssSpec.M, HashType.SHA1, RSASSAPSSTestVectors.salt), pssSpec.S); assertTrue(rsaPublicKey.checkSignature( pssSp... |
RSAOAEPPublicKey extends AbstractPublicKey { @NonNull @Override public Map<String, Object> toHash() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put("n", BigIntegers.asUnsignedByteArray(state.keyParame... | @Test public void toHash() throws Exception { AbstractPublicKey rsaPublicKey = oaepSpec.getPublicKey(); Map mapRSA = rsaPublicKey.toHash(); assertArrayEquals((byte[]) mapRSA.get("n"), oaepSpec.n); assertArrayEquals((byte[]) mapRSA.get("e"), oaepSpec.e); assertFalse(mapRSA.containsKey("mgf1Hash")); AbstractPublicKey goo... |
ItemCache { final void cleanUp() { Instant now = Instant.now(); records.values().forEach(r->r.checkExpiration(now)); } ItemCache(Duration maxAge); void shutdown(); @Nullable Approvable get(HashId itemId); @Nullable ItemResult getResult(HashId itemId); void put(Approvable item, ItemResult result); void update(HashId ite... | @Test public void cleanUp() throws Exception { ItemCache c = new ItemCache(Duration.ofMillis(10)); TestItem i1 = new TestItem(true); c.put(i1, ItemResult.UNDEFINED); assertEquals(i1, c.get(i1.getId())); Thread.sleep(11); c.cleanUp(); assertEquals(null, c.get(i1.getId())); } |
PostgresLedger implements Ledger { @Override public StateRecord createOutputLockRecord(long creatorRecordId, HashId newItemHashId) { StateRecord r = new StateRecord(this); r.setState(ItemState.LOCKED_FOR_CREATION); r.setLockedByRecordId(creatorRecordId); r.setId(newItemHashId); try { r.save(); return r; } catch (Failur... | @Test public void createOutputLockRecord() throws Exception { ledger.enableCache(true); StateRecord owner = ledger.findOrCreate(HashId.createRandom()); StateRecord other = ledger.findOrCreate(HashId.createRandom()); HashId id = HashId.createRandom(); StateRecord r1 = owner.createOutputLockRecord(id); r1.reload(); asser... |
PostgresLedger implements Ledger { @Override public void destroy(StateRecord record) { long recordId = record.getRecordId(); if (recordId == 0) { throw new IllegalStateException("can't destroy record without recordId"); } protect(() -> { inPool(d -> { d.update("DELETE FROM ledger WHERE id = ?", recordId); return null; ... | @Test public void destroy() throws Exception { StateRecord r1 = ledger.findOrCreate(HashId.createRandom()); r1.destroy(); assertNull(ledger.getRecord(r1.getId())); } |
ConsoleInterceptor { public static String copyOut(Block block) throws Exception { final ByteArrayOutputStream bos = new ByteArrayOutputStream(); final PrintStream printStream = new PrintStream(bos, true); PrintStream oldStream = System.out; PrintStream oldErr = System.err; System.setOut(printStream); System.setErr(prin... | @Test public void interceptStdout() throws Exception { String result = ConsoleInterceptor.copyOut(() ->{ System.out.print("hello world"); System.out.print('!'); System.out.println(); System.out.println("foobar"); }); assertEquals("hello world!\nfoobar\n", result); result = ConsoleInterceptor.copyOut( () ->{ System.out.... |
Binder extends HashMap<String, Object> implements Serializable { public boolean isFrozen() { return frozen; } Binder(Map copyFrom); Binder(); Binder(Object... keyValuePairs); static Binder fromKeysValues(Object... args); boolean isFrozen(); Double getDouble(String key); String getStringOrThrow(String key); String get... | @Test public void isFrozen() throws Exception { Binder b = new Binder(); b.put("hello", "world"); Binder x = b.getOrCreateBinder("inner"); x.put("foo", "bar"); assertFalse(b.isFrozen()); assertFalse(b.getBinder("inner").isFrozen()); b.freeze(); assertTrue(b.isFrozen()); assertTrue(b.getBinder("inner").isFrozen()); asse... |
Binder extends HashMap<String, Object> implements Serializable { @Deprecated public int getInt(String key) { return getIntOrThrow(key); } Binder(Map copyFrom); Binder(); Binder(Object... keyValuePairs); static Binder fromKeysValues(Object... args); boolean isFrozen(); Double getDouble(String key); String getStringOrT... | @Test public void getInt() throws Exception { Binder b = Binder.fromKeysValues( "i1", 100, "i2", "101", "l1", "1505774997427", "l2", 1505774997427L ); assertEquals(100, (int) b.getInt("i1",222)); assertEquals(101, (int) b.getInt("i2",222)); assertEquals(100, b.getIntOrThrow("i1")); assertEquals(101, b.getIntOrThrow("i2... |
AbstractKey implements Bindable, KeyMatcher { public byte[] fingerprint() { throw new RuntimeException("this key does not support fingerprints"); } byte[] encrypt(byte[] plain); byte[] decrypt(byte[] plain); byte[] sign(InputStream input, HashType hashType); byte[] sign(byte[] input, HashType hashType); boolean verify... | @Test public void fingerprint() throws Exception { PrivateKey k = TestKeys.privateKey(0); byte[] f1 = k.getPublicKey().fingerprint(); assertEquals(33, f1.length); byte[] f2 = k.fingerprint(); assertArrayEquals(f1, f2); assertEquals(AbstractKey.FINGERPRINT_SHA256, f1[0]); } |
Average { public double average() { if (n < 1) throw new IllegalStateException("too few samples"); return sum / n; } synchronized long update(double value); double average(); double stdev2(); double stdev(); long length(); double correctedStdev(); @Override String toString(); double variation(); } | @Test public void average() throws Exception { Average a = new Average(); for( int i=0; i<5; i++) a.update(i); for( int i=4; i>=0; i--) a.update(i); assertTrue(a.toString().startsWith("2.0±1.414213562373095")); assertEquals(1.490711985, a.correctedStdev(), 0.00001); } |
RunnableWithDynamicPeriod implements Runnable { public void restart() { waitsCount = 0; if (future != null) future.cancel(true); run(); } RunnableWithDynamicPeriod(Runnable lambda, List<Integer> periods, ScheduledExecutorService es); @Override void run(); void cancel(boolean b); void restart(); } | @Test public void testRestart() throws Exception { executorService.submit(() -> System.out.println("warm up executor")); Thread.sleep(1000); List<Integer> periods = Arrays.asList(0,100,100,100,200,400,800,1600,3200,6000); time = System.nanoTime(); AtomicInteger iTick = new AtomicInteger(0); AtomicInteger errorsCount = ... |
RunnableWithDynamicPeriod implements Runnable { public void cancel(boolean b) { synchronized (cancelled) { cancelled.set(true); } } RunnableWithDynamicPeriod(Runnable lambda, List<Integer> periods, ScheduledExecutorService es); @Override void run(); void cancel(boolean b); void restart(); } | @Test public void testCancel() throws Exception { executorService.submit(() -> System.out.println("warm up executor")); Thread.sleep(1000); List<Integer> periods = Arrays.asList(100,100,100,200); time = System.nanoTime(); AtomicInteger iTick = new AtomicInteger(0); AtomicInteger errorsCount = new AtomicInteger(0); Runn... |
BufferedLogger implements AutoCloseable { public List<Entry> slice(long id, int maxEntries) { List<Entry> copy = getCopy(); Entry start = new Entry(id); int fromIndex = Collections.binarySearch(copy, start); if (maxEntries > 0) fromIndex++; if (fromIndex < 0) fromIndex = 0; int toIndex = fromIndex + maxEntries; if (toI... | @Test public void slice() throws Exception { BufferedLogger log = new BufferedLogger(100); for (int i = 0; i < 10; i++) { log.log("line " + i); } log.flush(); List<BufferedLogger.Entry> all = log.getCopy(); List<BufferedLogger.Entry> entries = log.slice(all.get(5).id, 3); String result = str(entries); assertEquals("lin... |
BufferedLogger implements AutoCloseable { public @NonNull Entry log(String message) { Entry entry = new Entry(message); queue.add(entry); return entry; } BufferedLogger(int maxEntries); void e(String s); void flush(); boolean flush(long millis); PrintStream printTo(PrintStream ps, boolean printTimestamp); @NonNull Entr... | @Test public void log() throws Exception { BufferedLogger log = new BufferedLogger(3); for (int i = 0; i < 10; i++) { log.log("line " + i); } log.flush(); assertEquals("line 7,line 8,line 9", str(log.getCopy())); } |
Do { public static String snakeToCamelCase(String snakeString) { StringBuilder b = new StringBuilder(); for(String s: snakeString.split("_") ) { if(s.length() > 0 ) { b.append(Character.toUpperCase(s.charAt(0))); b.append(s.substring(1, s.length()).toLowerCase()); } } return b.toString(); } static byte[] read(String f... | @Test public void snakeToCamelCase() throws Exception { assertEquals("HelloWorld!", Do.snakeToCamelCase("hello_wORld_!")); assertEquals("Hello", Do.snakeToCamelCase("hello_")); assertEquals("Hello", Do.snakeToCamelCase("hello")); assertEquals("Hello", Do.snakeToCamelCase("_hello")); } |
Do { public static <T> T sample(Collection source) { int size = source.size(); if (size <= 0) return null; int i = Do.randomInt(size); if (source instanceof List && source instanceof RandomAccess) return (T) ((List) source).get(i); else return (T) source.toArray()[i]; } static byte[] read(String fileName); static byte... | @Test public void sample() throws Exception { HashSet<String> x = new HashSet<>(Do.listOf("aa", "bb", "cc", "cd")); HashSet<String> y = new HashSet<>(); ArrayList<String> z = new ArrayList<>(Do.listOf("aa", "bb", "cc", "cd")); HashSet<String> t = new HashSet<>(); int repetitions = 10000; for (int i = 0; i < repetitions... |
Do { public static int randomInt(int max) { return getRng().nextInt(max); } static byte[] read(String fileName); static byte[] read(InputStream inputStream); static String readToString(InputStream inputStream); static A checkSame(A oldValue, B newValue, Runnable onChanged); static T sample(Collection source); static S... | @Test public void randomInt() throws Exception { double sum = 0; int repetitions = 20000; int min = 10000, max = -1000; for(int i=0; i < repetitions; i++ ) { int x = Do.randomInt(100); sum += x; if( x < min ) min = x; if( x > max ) max = x; } sum /= repetitions; assertThat( sum, is(closeTo(50, 0.9))); assertThat(min, i... |
DeferredResult { public DeferredResult success(Handler handler) { synchronized (successHandlers) { successHandlers.add(handler); } if (done && success) invokeSuccess(); return this; } DeferredResult success(Handler handler); DeferredResult failure(Handler handler); DeferredResult done(Handler handler); void sendSucces... | @Test public void success() throws Exception { DeferredResult dr = new DeferredResult(); dr.success( (text-> assertEquals("hello", text))); dr.sendSuccess("hello"); } |
AsyncEvent { public void fire(T result) { synchronized (mutex) { this.result = result; fired = true; for (Consumer<T> consumer : consumers) pool.execute(() -> consumer.accept(result)); consumers.clear(); mutex.notifyAll(); } } AsyncEvent<T> addConsumer(Consumer<T> consumer); void fire(T result); boolean isFired(); @De... | @Test public void fire() throws Exception { for(int n=0; n<500; n++) { AsyncEvent<Integer> event = new AsyncEvent<>(); int values[] = new int[] { 0, 0}; CountDownLatch latch = new CountDownLatch(2); event.addConsumer(i -> { values[0] = i; latch.countDown(); }); event.addConsumer(i -> { values[1] = i; latch.countDown();... |
AbstractKey implements Bindable, KeyMatcher { public boolean matchAnonymousId(@NonNull byte[] packedId) throws IOException { assert (packedId.length == 64); HMAC hmac = new HMAC(fingerprint()); hmac.update(packedId, 0, 32); byte[] idDigest = Arrays.copyOfRange(packedId, 32, 64); return Arrays.equals(hmac.digest(), idDi... | @Test public void matchAnonymousId() throws Exception { PrivateKey k1 = TestKeys.privateKey(0); byte[] id1 = k1.createAnonymousId(); byte[] id12 = k1.createAnonymousId(); PrivateKey k2 = TestKeys.privateKey(1); byte[] id2 = k2.createAnonymousId(); assertEquals(64, id1.length); assertEquals(64, id12.length); assertEqual... |
BossConnector extends BasicConnector implements Connector { @Override public void send(Map<String, Object> data) throws IOException { if( closed.get() ) throw new IOException("connection closed"); bossOut.write(data); } BossConnector(InputStream in, OutputStream out); @Override void send(Map<String, Object> data); @Ove... | @Test public void send() throws Exception { StreamConnector sa = new StreamConnector(); BossConnector bsc = new BossConnector(sa.getInputStream(), sa.getOutputStream()); bsc.send(Do.map("hello", "мыльня")); Map<String, Object> res = bsc.receive(); assertEquals(1, res.size()); assertEquals("мыльня", res.get("hello")); }... |
JsonConnector extends BasicConnector implements Connector { @Override public void send(Map<String, Object> data) throws IOException { if (closed.get()) throw new IOException("connection closed"); out.write((toJsonString(data) + "\n").getBytes()); } JsonConnector(InputStream in, OutputStream out); @Override void send(Ma... | @Test(timeout = 100) public void send() throws Exception { StreamConnector sa = new StreamConnector(); JsonConnector jsc = new JsonConnector(sa.getInputStream(), sa.getOutputStream()); jsc.send(Do.map("hello", "мыльня")); Map<String, Object> res = jsc.receive(); assertEquals(1, res.size()); assertEquals("мыльня", res.g... |
BiMapper { public @NonNull <T> T serialize(Object x, BiSerializer serializer) { if (x instanceof String || x instanceof Number || x instanceof Boolean || x == null) return (T) x; Class<?> klass = x.getClass(); if (klass.isArray() && !(klass.getComponentType() == byte.class)) { x = Arrays.asList((Object[]) x); } if (x i... | @Test public void serialize() throws Exception { ZonedDateTime now = ZonedDateTime.now(); Binder res = DefaultBiMapper.serialize( Binder.of( "time", now, "hello", "world" ) ); assertEquals("world", res.get("hello")); assertEquals("unixtime", res.getStringOrThrow("time", "__type")); Binder restored = DefaultBiMapper.des... |
Informer { public void post(Object event) { int result; int processedCount = invokeCollection(weakInvocations, event); processedCount += invokeCollection(strongInvocations, event); if (processedCount == 0 && !(event instanceof LostEvent)) { post(new LostEvent(event)); } } Informer(); Informer(ExceptionListener listene... | @Test public void testPost() throws Exception { Receiver2 receiver = new Receiver2(); informer.registerStrong(receiver); informer.post(123); assertEquals(0, Receiver2.stringCalls); assertEquals(1, Receiver2.objectCalls); assertEquals(123, receiver.lastObject); informer.post("test1"); assertEquals(2, Receiver2.stringCal... |
Informer { public void postAfter(final Object event, final long millis) { new Thread(new Runnable() { @Override public void run() { try { Thread.currentThread().sleep(millis); post(event); } catch (InterruptedException e) { } } }).start(); } Informer(); Informer(ExceptionListener listener); void post(Object event); vo... | @Test public void testPostAfter() throws Exception { Receiver1 r1 = new Receiver1(); informer.registerWeak(r1); informer.postAfter(11, 100); assertEquals(0, Receiver1.lostCount); sleep(40); assertEquals(0, Receiver1.lostCount); sleep(70); assertEquals(1, Receiver1.lostCount); } |
Informer { public void registerWeak(Object subscriber) { register(subscriber, true); } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Objec... | @Test public void testRegisterWeak() throws Exception { assertEquals(0, Receiver1.lostCount); informer.registerWeak(new Receiver1()); System.gc(); informer.post(11); assertEquals(0, Receiver1.lostCount); } |
Informer { public void registerStrong(Object subscriber) { register(subscriber, false); } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Ob... | @Test public void testRegisterStrong() throws Exception { assertEquals(0, Receiver1.lostCount); informer.registerStrong(new Receiver1()); informer.post(11); assertEquals(1, Receiver1.lostCount); } |
Informer { public boolean unregister(Object subscriber) { boolean found = (weakInvocations.remove(subscriber) != null); found = found || (strongInvocations.remove(subscriber) != null); return found; } Informer(); Informer(ExceptionListener listener); void post(Object event); void postAfter(final Object event, final lo... | @Test public void testUnregister() throws Exception { assertEquals(0, Receiver1.lostCount); Receiver1 r1 = new Receiver1(); informer.registerWeak(r1); informer.unregister(r1); informer.post(11); assertEquals(0, Receiver1.lostCount); informer.registerStrong(r1); informer.unregister(r1); informer.post(11); assertEquals(0... |
Safe58 { public static String encode(byte[] input) { if (input.length == 0) { return ""; } input = copyOfRange(input, 0, input.length); int zeroCount = 0; while (zeroCount < input.length && input[zeroCount] == 0) { ++zeroCount; } byte[] temp = new byte[input.length * 2]; int j = temp.length; int startAt = zeroCount; wh... | @Test public void encode() { for(int i=0; i<100;i++) { byte [] src = Do.randomBytes(256+Do.randomInt(1024)); assertArrayEquals(src, Safe58.decode(Safe58.encode(src))); } } |
KeyAddress implements KeyMatcher { @Override public boolean isMatchingKey(AbstractKey key) { KeyAddress other = new KeyAddress(key, 0, _isLong); if (other.keyMask != keyMask) return false; if (!Arrays.equals(keyDigest, other.keyDigest)) return false; return true; } KeyAddress(); KeyAddress(AbstractKey key, int typeMar... | @Test public void isMatchingKey() throws KeyAddress.IllegalAddressException { testMatch(true); testMatch(false); } |
Safe58 { public static byte[] decode(String input) { return decode(input,false); } static String encode(byte[] input); static byte[] decode(String input); static byte[] decode(String input, boolean strict); } | @Test public void decode() { byte[] ok = Safe58.decode("Helloworld"); assertArrayEquals(ok,Safe58.decode("HellOwOr1d")); assertArrayEquals(ok,Safe58.decode("He1IOw0r1d")); assertArrayEquals(ok,Safe58.decode("He!|Ow0r|d")); } |
CLIMain { public static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners) throws IOException { return saveContract(contract,fileName,fromPackedTransaction,addSigners,null); } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpCl... | @Test public void checkTransactionPack() throws Exception { Contract r = new Contract(ownerKey1); r.seal(); Contract c = r.createRevision(ownerKey1); Contract n = c.split(1)[0]; n.seal(); c.seal(); c.addNewItems(n); String path = rootPath + "/testtranspack.unicon"; c.seal(); Files.deleteIfExists(Paths.get(path)); CLIMa... |
CLIMain { private static void exportPublicKeys(Contract contract, String roleName, String fileName, boolean base64) throws IOException { if (fileName == null) { if (testMode && testRootPath != null) { fileName = testRootPath + "Universa_" + roleName + "_public_key"; } else { fileName = "Universa_" + roleName + "_public... | @Test public void exportPublicKeys() throws Exception { String role = "owner"; callMain( "-e", basePath + "contract_to_export.unicon", "--extract-key", role); System.out.println(output); assertTrue (output.indexOf(role + " export public keys ok") >= 0); assertEquals(0, errors.size()); } |
CLIMain { private static void updateFields(Contract contract, HashMap<String, String> fields) throws IOException { for (String fieldName : fields.keySet()) { report("update field: " + fieldName + " -> " + fields.get(fieldName)); Binder data = null; Object obj = null; try { XStream xstream = new XStream(new DomDriver())... | @Test public void updateFields() throws Exception { ZonedDateTime zdt = ZonedDateTime.now().plusHours(1); String field1 = "definition.issuer"; String value1 = "<definition.issuer>\n" + " <SimpleRole>\n" + " <keys isArray=\"true\">\n" + " <item>\n" + " <KeyRecord>\n" + " <name>Universa</name>\n" + " <key>\n" + " <RSAPub... |
CLIMain { public static Contract downloadContract(String url) { report("downloading from " + url); return null; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static vo... | @Test public void downloadContract() throws Exception { callMain("-d", "www.mainnetwork.io"); System.out.println(output); assertTrue (output.indexOf("downloading from www.mainnetwork.io") >= 0); assertEquals(0, errors.size()); } |
CLIMain { private static void checkContract(Contract contract) { if (!contract.isOk()) { reporter.message("The capsule is not sealed properly:"); contract.getErrors().forEach(e -> reporter.error(e.getError().toString(), e.getObjectName(), e.getMessage())); } Yaml yaml = new Yaml(); if (reporter.isVerboseMode()) { repor... | @Test public void checkContract() throws Exception { callMain("-ch", basePath + "contract1.unicon"); System.out.println(output); assertEquals(0, errors.size()); } |
KeyInfo { public AbstractKey unpackKey(byte[] data) throws EncryptionError { switch (algorythm) { case RSAPublic: return new PublicKey(data, this); case RSAPrivate: return new PrivateKey(data, this); case AES256: return new SymmetricKey(data, this); } throw new EncryptionError("can't unpack key: " + this); } KeyInfo(Al... | @Test public void unpackKey() throws Exception { AbstractKey k1 = TestKeys.privateKey(3).getPublicKey(); AbstractKey kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); k1 = SymmetricKey.fromPassword("helluva", 4096); kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); k1 = TestKeys.privateK... |
CLIMain { @Deprecated public static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction) throws IOException { List<ErrorRecord> errors = contract.getErrors(); if (errors.size() > 0) { report("contract has errors and can't be submitted for registration"); report("contract id: " + contrac... | @Test public void revokeContractVirtual() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(rootPath+"_xer0yfe2nn1xthc.private.unikey"); c.addSignerKeyFromFile(rootPath + "keys/u_key.private.unikey"); PrivateKey goodKey = c.getKeysToSignWith().iterator()... |
CLIMain { public static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key) throws IOException { report("keys num: " + key.length); Contract tc = ContractsService.createRevocation(contract, key); Parcel parcel = prepareForRegisterContract(t... | @Test public void revokeContract() throws Exception { String contractFileName = basePath + "contract_for_revoke3.unicon"; String uContract = getApprovedUContract(); callMain2("--register", contractFileName, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); Contract c = CLIMain.loa... |
CLIMain { public static Contract loadContract(String fileName, Boolean fromPackedTransaction) throws IOException { Contract contract = null; File pathFile = new File(fileName); if (pathFile.exists()) { Path path = Paths.get(fileName); byte[] data = Files.readAllBytes(path); try { if (fromPackedTransaction) { contract =... | @Test public void revokeContractWithoutKey() throws Exception { String contractFileName = basePath + "contract_for_revoke1.unicon"; String uContract = getApprovedUContract(); callMain2("--register", contractFileName, "--verbose", "--u", uContract, "--k", rootPath + "keys/stepan_mamontov.private.unikey"); callMain2("-re... |
Syntex1 extends Digest { @Override public int getLength() { return 36; } @Override int getLength(); } | @Test public void testBasics() throws Exception { Syntex1 s = new Syntex1(); s.update("Hello world"); byte[] d1 = s.digest(); assertEquals(36, s.getLength()); byte[] d2 = new Syntex1().digest("Fello world"); assertEquals(36, d2.length); byte[] d3 = new Syntex1().digest("Hello world"); assertArrayEquals(d1, d3); assertT... |
CLIMain { private static void printWallets(List<Wallet> wallets) { reporter.message(""); List<Contract> foundContracts = new ArrayList<>(); for (Wallet wallet : wallets) { foundContracts.addAll(wallet.getContracts()); reporter.message("found wallet: " + wallet.toString()); reporter.verbose(""); HashSet<WalletValueModel... | @Ignore @Test public void printWallets() throws Exception { System.out.println("\n\n"); callMain("-f", "/home/flint/w/uniclient-test", "--verbose"); System.out.println(output); System.out.println("\n\n"); } |
PrivateKey extends AbstractKey { public byte[] pack() { @NonNull final Map<String, Object> params = privateKey.toHash(); return Boss.dumpToArray(new Object[]{ TYPE_PRIVATE, params.get("e"), params.get("p"), params.get("q") }); } PrivateKey(byte[] packedBinaryKey, KeyInfo info); PrivateKey(byte[] packedBinaryKey); Pri... | @Test public void serializationTest() throws Exception { byte[] packedPublicKey = Do.decodeBase64(publicKey64); PublicKey publicKey = new PublicKey(packedPublicKey); byte[] packedPublicKey2 = publicKey.pack(); assertArrayEquals(packedPublicKey, packedPublicKey2); byte[] packedPrivateKey = Do.decodeBase64(TestKeys.binar... |
RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] decrypt(byte[] ciphertext) throws EncryptionError { if (state == null) { throw new IllegalStateException(); } else { try { return state.decryptor.processBlock(ciphertext, 0, ciphertext.length); } catch (InvalidCipherTextException e) { throw new Encr... | @Test public void decrypt() throws Exception { AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); AbstractPublicKey rsaPublicKey = rsaPrivateKey.getPublicKey(); ((RSAOAEPPrivateKey) rsaPrivateKey).resetDecryptor(); assertArrayEquals(rsaPrivateKey.decrypt(oaepSpec.C), oaepSpec.M); ((RSAOAEPPublicKey) rsaPublic... |
PrivateKey extends AbstractKey { public static PrivateKey unpackWithPassword(byte[] packedBinary, String password) throws EncryptionError { List params = Boss.load(packedBinary); if ((Integer) params.get(0) == TYPE_PRIVATE) { return new PrivateKey(packedBinary); } else if ((Integer) params.get(0) == TYPE_PUBLIC) { thro... | @Test public void passwordProtectedJsCompatibilityTest() throws Exception { byte[] encrypted = Base64.decodeCompactString("NhDIoIYBvB1jb20uaWNvZGljaS5jcnlwdG8uUHJpdmF0ZUtleVtITUFDX1NIQTI1NsQaAe01NLf/Ffcye5nVmAOsYV5uy/Q/OXqbVfH4baSo5rgdtYl3xmTrkwfHEerHVjyB/raQcJ6b96k3oVIHu6I/wDtZ3TMkQ8gpjzlEnzOs6LQ+0OzObrjxFfpiXZdPMLzu4... |
PBKDF2 { public static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen) { return new PBKDF2(hash, password, salt, c, dkLen).compute(); } private PBKDF2(Class<? extends Digest> hashClass,
String password,
byte[] salt,
int c... | @Test public void computeSha512() { String src = "test $pbkdf$pbkdf2-sha512$5000$26$KFuMDXmo$yPsu5qmQto99vDqAMWnldNuagfVl5OhPr6g="; String[] parts = src.split("\\$"); String password = parts[0].trim(); int c = Integer.valueOf(parts[3]); int dkLen = Integer.valueOf(parts[4]); byte[] salt = Do.decodeBase64(parts[5]); byt... |
KeyRing implements Capsule.KeySource, Bindable { @Override @NonNull public Collection<AbstractKey> findKey(KeyInfo keyInfo) { final ArrayList<AbstractKey> result = new ArrayList<>(); for( AbstractKey k: keys) { final KeyInfo ki = k.info(); if( ki.matchType(keyInfo) ) { if( ki.matchTag(keyInfo) ) result.add(0, k); else ... | @Test public void findKey() throws Exception { KeyInfo i1 = new KeyInfo(KeyInfo.PRF.HMAC_SHA256, 1024, null, null); AbstractKey pk1 = i1.derivePassword("helluva"); KeyInfo i2 = new KeyInfo(KeyInfo.PRF.HMAC_SHA256, 1025, null, "the tag".getBytes()); AbstractKey pk2 = i2.derivePassword("helluva"); assertEquals(i2.getTag(... |
SymmetricKey extends AbstractKey implements Serializable, Hashable { public byte[] etaEncrypt(byte[] data) throws EncryptionError { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { final EtaEncryptingStream s = etaEncryptStream(bos); s.write(data); s.end(); return bos.toByteArray(); } catch (IOException e... | @Test public void etaEncrypt() throws Exception { SymmetricKey k = new SymmetricKey(); byte[] plainText = "Hello, world!".getBytes(); byte[] cipherText = k.etaEncrypt(plainText); assertEquals(16 + 32 + plainText.length, cipherText.length); byte[] decryptedText = k.etaDecrypt(cipherText); assertArrayEquals(plainText, de... |
SymmetricKey extends AbstractKey implements Serializable, Hashable { public static byte[] xor(byte[] src, int value) { byte[] result = new byte[src.length]; for (int i = 0; i < src.length; i++) result[i] = (byte) ((src[i] ^ value) & 0xFF); return result; } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[]... | @Test public void xor() throws Exception { byte[] test = new byte[]{0, 0x55, (byte) 0xFF}; byte[] src = new byte[]{0, 0x55, (byte) 0xFF}; test = SymmetricKey.xor(test, 0); assertArrayEquals(test, src); test = SymmetricKey.xor(test, 0xFF); assertArrayEquals(new byte[]{(byte) 0xFF, (byte) 0xAA, 0}, test); test = Symmetri... |
Decimal extends Number implements Comparable<Number> { public Decimal[] divideAndRemainder(BigDecimal divisor) { BigDecimal[] result = value.divideAndRemainder(divisor); return new Decimal[]{new Decimal(result[0]), new Decimal(result[1])}; } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(Bi... | @Test public void divideAndRemainder() throws Exception { Decimal x = new Decimal("1000000000000"); Decimal[] dr = x.divideAndRemainder(new Decimal(3)); assertEquals("333333333333", dr[0].toString()); assertEquals(1, dr[1].intValue()); } |
Decimal extends Number implements Comparable<Number> { public Decimal ulp() { return new Decimal(value.ulp()); } Decimal(); Decimal(String stringValue); Decimal(long longValue); Decimal(BigDecimal bigDecimalValue); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double d... | @Test public void ulp() throws Exception { Decimal x = new Decimal("1000000000000.0000000000000000001"); assertEquals( 1e-19,x.ulp().doubleValue(), 0); } |
SimpleRole extends Role { public SimpleRole cloneAs(String name,Contract contract) { SimpleRole r = new SimpleRole(name,contract); keyRecords.values().forEach(kr -> r.addKeyRecord(kr)); anonymousIds.forEach(aid -> r.anonymousIds.add(aid)); keyAddresses.forEach(keyAddr -> r.keyAddresses.add(keyAddr)); return r; } @Depre... | @Test public void testCloneAsAddressRole() throws Exception { Set<KeyAddress> keyAddresses = new HashSet<>(); keyAddresses.add(new KeyAddress(keys.get(0).getPublicKey(), 0, true)); SimpleRole sr = new SimpleRole("tr1",null, keyAddresses); SimpleRole r1 = sr.cloneAs("tr2",null); SimpleRole r2 = r1.cloneAs("tr1",null); a... |
RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public AbstractPublicKey getPublicKey() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return state.publicKey; } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashT... | @Test public void getPublicKey() throws Exception { AbstractPublicKey randomPublicKey4096 = randomPrivateKey4096.getPublicKey(); assertTrue(randomPublicKey4096 instanceof RSAOAEPPublicKey); AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); AbstractPublicKey rsaPublicKey = rsaPrivateKey.getPublicKey(); ((RSAO... |
SimpleRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(anonymousIds.size() == 0 && keyRecords.size() + keyAddresses.size() == 1) { if(keyRecords.size() == 1) { return keyRec... | @Test public void testGetSimpleAddress() throws Exception { Set<Object> keyAddresses = new HashSet<>(); keyAddresses.add(keys.get(0).getPublicKey().getShortAddress()); SimpleRole sr = new SimpleRole("tr1",null, keyAddresses); assertEquals(sr.getSimpleAddress(),keyAddresses.iterator().next()); keyAddresses.add(keys.get(... |
RoleLink extends Role { @Override public <T extends Role> T resolve() { return resolve(true); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Ro... | @Test public void resolve() throws Exception { Contract c = new Contract(); SimpleRole s1 = new SimpleRole("owner",c); c.addRole(s1); RoleLink r1 = new RoleLink("lover",c, "owner"); c.addRole(r1); RoleLink r2 = r1.linkAs("mucker"); assertSame(s1, s1.resolve()); assertSame(s1, r1.resolve()); assertSame(s1, r2.resolve())... |
RoleLink extends Role { @Override public Binder serialize(BiSerializer s) { return super.serialize(s).putAll( "name", getName(), "target_name", roleName ); } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(String name, Contract contract, String roleName); @De... | @Test public void serialize() throws Exception { RoleLink r1 = new RoleLink("name", "target"); r1.addRequiredReference("ref", Role.RequiredMode.ALL_OF); Binder s = DefaultBiMapper.serialize(r1); RoleLink r2 = DefaultBiMapper.deserialize(s); assertEquals(r1, r2); assertEquals(r1.getName(), r2.getName()); } |
RoleLink extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { Role r = resolve(ignoreRefs); if (r != null && r != this) return r.getSimpleAddress(ignoreRefs); return null; } private RoleLink(); RoleLink(String name,Contract contract); @Deprecated RoleLink(String name); RoleLink(Strin... | @Test public void testGetSimpleAddress() throws Exception { Set<Object> keyAddresses = new HashSet<>(); keyAddresses.add(TestKeys.publicKey(0).getLongAddress()); Contract c = new Contract(); SimpleRole sr = new SimpleRole("sr",c, keyAddresses); c.addRole(sr); RoleLink rl = new RoleLink("rl",c,sr.getName()); c.addRole(r... |
ListRole extends Role { public void setMode(Mode newMode) { if (newMode != Mode.QUORUM) this.mode = newMode; else throw new IllegalArgumentException("Only ANY or ALL of the modes should be set."); } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract... | @Test public void shouldNotAllowToSetQuorum() { ListRole listRole = new ListRole("roles"); try { listRole.setMode(ListRole.Mode.QUORUM); fail("Expected exception to be thrown."); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().equalsIgnoreCase("Only ANY or ALL of the modes should be set.")); } } |
ListRole extends Role { @Override @Nullable KeyAddress getSimpleAddress(boolean ignoreRefs) { if(!ignoreRefs && (requiredAnyReferences.size() > 0 || requiredAllReferences.size() > 0)) return null; if(roles.size() == 1 && (mode != Mode.QUORUM || quorumSize == 1)) { return roles.iterator().next().getSimpleAddress(ignoreR... | @Test public void testGetSimpleAddress() throws Exception { Set<Object> keyAddresses = new HashSet<>(); keyAddresses.add(TestKeys.publicKey(0).getLongAddress()); SimpleRole sr = new SimpleRole("sr", keyAddresses); ListRole lr = new ListRole(); lr.addRole(sr); lr.setMode(ListRole.Mode.ALL); assertEquals(lr.getSimpleAddr... |
TransactionPack implements BiSerializable { public static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions) throws IOException { Object x = Boss.load(packOrContractBytes); if (x instanceof TransactionPack) { return (TransactionPack) x; } if (!allowNonTransactions) throw new IOException("e... | @Test public void deserializeOldContract() throws Exception { TransactionPack tp = TransactionPack.unpack(c.sealAsV2()); checkSimplePack(tp); } |
TransactionPack implements BiSerializable { public void setContract(Contract c) { if (contract != null) throw new IllegalArgumentException("the contract is already added"); contract = c; packedBinary = null; extractAllSubItemsAndReferenced(c); c.setTransactionPack(this); for (PrivateKey key : c.getKeysToSignWith()) add... | @Test public void serializeNew() throws Exception { TransactionPack tp = new TransactionPack(); tp.setContract(c); checkSimplePack(tp); } |
ContractsService { public synchronized static Contract createRevocation(Contract c, PrivateKey... keys) { Contract tc = new Contract(); Contract.Definition cd = tc.getDefinition(); cd.setExpiresAt(tc.getCreatedAt().plusDays(30)); SimpleRole issuerRole = new SimpleRole("issuer",tc); for (PrivateKey k : keys) { KeyRecord... | @Test public void badRevoke() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); c.addSignerKeyFromFile(rootPath+"_xer0yfe2nn1xthc.private.unikey"); c.seal(); PrivateKey issuer = TestKeys.privateKey(2); Contract tc = c.createRevocation(issuer); boolean result = tc.check(); asse... |
RSAOAEPPrivateKey extends AbstractPrivateKey { @Override public byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt) throws IllegalStateException, IOException { if (state == null) { throw new IllegalStateException(); } else { final Digest primaryDigest = hashType.makeDigest(); final PSSSigner signer... | @Test public void sign() throws Exception { AbstractPrivateKey rsaPrivateKey = pssSpec.getPrivateKey(); assertArrayEquals(rsaPrivateKey.sign(pssSpec.M, HashType.SHA1, RSASSAPSSTestVectors.salt), pssSpec.S); } |
ContractsService { public synchronized static Contract createNotaryContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys) { Contract notaryContract = new Contract(); notaryContract.setApiLevel(3); Contract.Definition cd = notaryContract.getDefinition(); cd.setExpiresAt(notaryContract.getCreatedAt().plusMonths(6... | @Test public void goodNotary() throws Exception { Set<PrivateKey> martyPrivateKeys = new HashSet<>(); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PublicKey> martyPublicKeys = new HashSet<>(); Set<PublicKey> stepaPublicKeys = new HashSet<>(); martyPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/marty... |
ContractsService { @Deprecated public synchronized static Contract createTokenContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount, Double minValue, String currency, String name, String description) { return createTokenContract(issuerKeys, ownerKeys, new BigDecimal(amount), new BigDecimal(minVal... | @Test public void goodToken() throws Exception { Set<PrivateKey> martyPrivateKeys = new HashSet<>(); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PublicKey> martyPublicKeys = new HashSet<>(); Set<PublicKey> stepaPublicKeys = new HashSet<>(); martyPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/marty_... |
ContractsService { @Deprecated public synchronized static Contract createShareContract(Set<PrivateKey> issuerKeys, Set<PublicKey> ownerKeys, String amount) { return createShareContract(issuerKeys, ownerKeys, new BigDecimal(amount)); } synchronized static Contract createRevocation(Contract c, PrivateKey... keys); @Depr... | @Test public void goodShare() throws Exception { Set<PrivateKey> martyPrivateKeys = new HashSet<>(); Set<PrivateKey> stepaPrivateKeys = new HashSet<>(); Set<PublicKey> martyPublicKeys = new HashSet<>(); Set<PublicKey> stepaPublicKeys = new HashSet<>(); martyPrivateKeys.add(new PrivateKey(Do.read(rootPath + "keys/marty_... |
SplitJoinPermission extends Permission { @Override public void deserialize(Binder data, BiDeserializer deserializer) { super.deserialize(data, deserializer); initFromParams(); } SplitJoinPermission(Role role, Binder params); private SplitJoinPermission(); @Override void deserialize(Binder data, BiDeserializer deserial... | @Test public void shouldNotSplitWithWrongDataAmountSerialize() throws Exception { Contract c = createCoin(); c.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(c, true); Contract c2 = c.split(1)[0]; sealCheckTrace(c2, true); Binder sd2 = DefaultBiMapper.serialize(c2); Binder state = (Binder) sd2.get("state"); ass... |
ModifyDataPermission extends Permission { public ModifyDataPermission addField(String fieldName, List<String> values) { this.fields.put(fieldName, values); return this; } ModifyDataPermission(); ModifyDataPermission(Role role, Binder params); ModifyDataPermission addField(String fieldName, List<String> values); void a... | @Test public void modifyDataAllowed() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); contract.getStateData().put("field_to_be_changed", "value1"); ModifyDataPermission modifyDataPermission = new ModifyDataPermission(contract.getRole("owner"), new Binder()); modifyDataPermission.addField("f... |
RSAOAEPPrivateKey extends AbstractPrivateKey { @NonNull @Override public Map<String, Object> toHash() throws IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { return Collections.unmodifiableMap(new HashMap<String, Object>() {{ put("e", BigIntegers.asUnsignedByteArray(state.keyPara... | @Test public void toHash() throws Exception { AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); Map mapRSA = rsaPrivateKey.toHash(); assertArrayEquals((byte[]) mapRSA.get("e"), oaepSpec.e); assertArrayEquals((byte[]) mapRSA.get("p"), oaepSpec.p); assertArrayEquals((byte[]) mapRSA.get("q"), oaepSpec.q); asser... |
Permission implements BiSerializable, Comparable<Permission> { public void setId(@NonNull String id) { if( this.id != null && !this.id.equals(id) ) throw new IllegalStateException("permission id is already set"); this.id = id; } protected Permission(); protected Permission(String name, Role role); protected Permissi... | @Test public void contractGetPermission() throws Exception { Contract contract = new Contract(TestKeys.privateKey(0)); Contract contract2 = new Contract(TestKeys.privateKey(0)); ChangeNumberPermission changeNumberPermission = new ChangeNumberPermission(new RoleLink("@owner", "owner"), Binder.of( "field_name", "field1",... |
ExtendedSignature { static public byte[] sign(PrivateKey key, byte[] data) { return sign(key, data, true); } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] c... | @Test public void sign() throws Exception { byte[] data = "Hello world".getBytes(); PrivateKey k = TestKeys.privateKey(3); byte [] signature = ExtendedSignature.sign(k, data); PublicKey pubKey = k.getPublicKey(); ExtendedSignature es = ExtendedSignature.verify(pubKey, signature, data); assertNotNull(es); assertAlmostSa... |
UnikeyFactory { @Nullable static RSAOAEPPrivateKey rsaOaepPKFromUnikey(@NonNull byte[] bytes) { assert bytes != null; try { final ArrayList unpackedFromBoss = Boss.load(bytes); assert ((Integer) unpackedFromBoss.get(0)) == 0; final byte[] e = ((Bytes) unpackedFromBoss.get(1)).toArray(), p = ((Bytes) unpackedFromBoss.ge... | @Test public void testFromUnikeyRSAOAEP() throws Exception { final RSAOAEPPrivateKey pk1 = UnikeyFactory.rsaOaepPKFromUnikey(pk1Bytes); assertNotNull(pk1); assertArrayEquals( pk1E, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getPublicExponent())); assertArrayEquals( pk1P, BigIntegers.asUnsignedByteArray(pk1... |
ExtendedSignature { public static PublicKey extractPublicKey(byte[] signature) { Binder src = Boss.unpack(signature); PublicKey publicKey = null; byte[] exts = src.getBinaryOrThrow("exts"); Binder b = Boss.unpack(exts); try { byte[] publicKeyBytes = b.getBinaryOrThrow("pub_key"); publicKey = new PublicKey(publicKeyByte... | @Test public void extractPublicKey() throws Exception { byte[] data = "Hello world".getBytes(); PrivateKey k = TestKeys.privateKey(3); byte [] signature = ExtendedSignature.sign(k, data); PublicKey pubKey = k.getPublicKey(); ExtendedSignature es = ExtendedSignature.verify(pubKey, signature, data); assertNotNull(es); as... |
Contract implements Approvable, BiSerializable, Cloneable { public static Contract fromDslFile(String fileName) throws IOException { Yaml yaml = new Yaml(); try (FileReader r = new FileReader(fileName)) { Binder binder = Binder.from(DefaultBiMapper.deserialize((Map) yaml.load(r))); return new Contract().initializeWithD... | @Test public void fromYamlFile() throws Exception { Contract c = Contract.fromDslFile(rootPath + "simple_root_contract.yml"); assertProperSimpleRootContract(c); } |
Contract implements Approvable, BiSerializable, Cloneable { public void addSignerKeyFromFile(String fileName) throws IOException { addSignerKey(new PrivateKey(Do.read(fileName))); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Co... | @Test public void calculateProcessingCostSimpleBreak() throws Exception { Contract contract = createCoin100apiv3(); contract.addSignerKeyFromFile(PRIVATE_KEY_PATH); sealCheckTrace(contract, true); int costShouldBe = 28; boolean exceptionThrown = false; try { processContractAsItWillBeOnTheNode(contract, 10); } catch (Qu... |
Contract implements Approvable, BiSerializable, Cloneable { public int getProcessedCost() { return getQuantiser().getQuantaSum(); } Contract(byte[] sealed, @NonNull TransactionPack pack); Contract(Binder data, @NonNull TransactionPack pack); Contract(byte[] data); Contract(byte[] sealed, Binder data, TransactionPack... | @Test public void calculateSplit7To2ProcessingCost_key2048() throws Exception { Contract processingContract = calculateSplit7To2ProcessingCost(PRIVATE_KEY2048_PATH, true); int costShouldBeForSplit = 188; assertEquals(costShouldBeForSplit, processingContract.getProcessedCost()); }
@Test public void calculateSplit7To2Pro... |
Main { private void startNode() throws SQLException, IOException { config.setConsensusConfigUpdater((config, n) -> { int negative; int positive; if(n < 3) { negative = 1; positive = n; } else if(n < 10) { negative = 2; positive = n-1; } else { positive = (int) Math.ceil(n * 0.9); negative = n + 1 - positive; } int resy... | @Test public void startNode() throws Exception { String path = new File("src/test_node_config_v2/node1").getAbsolutePath(); System.out.println(path); String[] args = new String[]{"--test", "--config", path, "--nolog"}; Main main = new Main(args); main.waitReady(); BufferedLogger l = main.logger; Client client = new Cli... |
UnikeyFactory { @NonNull static byte[] toUnikey(@NonNull RSAOAEPPrivateKey privateKey) { assert privateKey != null; return privateKey.pack(); } @Nullable static PrivateKey fromUnikey(@NonNull byte[] bytes); @NonNull static byte[] toUnikey(@NonNull PrivateKey privateKey); } | @Test public void testToUnikeyRSAOAEP() throws Exception { final RSAOAEPPrivateKey pk1 = new RSAOAEPPrivateKey( pk1E, pk1P, pk1Q, HashType.SHA1, HashType.SHA1, new SecureRandom()); assertArrayEquals( pk1Bytes, UnikeyFactory.toUnikey(pk1)); } |
RSAOAEPDigestFactory { @Nullable public static Digest getDigestByName(String digestName) { Class digestClass = (Class) supportedDigestAlgorithmClassesByName.get(digestName); if (digestClass == null) { return null; } else { try { return (Digest) (digestClass.newInstance()); } catch (InstantiationException | IllegalAcces... | @Test public void getDigestByName() throws Exception { Digest dNoDigest1 = RSAOAEPDigestFactory.getDigestByName(""); assertNull(dNoDigest1); Digest dNoDigest2 = RSAOAEPDigestFactory.getDigestByName("Missing hash"); assertNull(dNoDigest2); Digest dSHA1 = RSAOAEPDigestFactory.getDigestByName("SHA-1"); assertArrayEquals( ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.