method2testcases
stringlengths 118
6.63k
|
---|
### Question:
RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions withUserData(byte[] unencodedData) { int length = checkNotNull(unencodedData, "unencodedData").length; checkArgument(length > 0, "userData cannot be empty"); checkArgument(length <= 16 * 1024, "userData cannot be larger than 16kb"); formParameters.put("UserData", base64().encode(unencodedData)); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer:
@Test public void testWithUserData() { RunInstancesOptions options = new RunInstancesOptions(); options.withUserData("test".getBytes()); assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of("dGVzdA==")); }
@Test public void testWithUserDataStatic() { RunInstancesOptions options = withUserData("test".getBytes()); assertEquals(options.buildFormParameters().get("UserData"), ImmutableList.of("dGVzdA==")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithUserDataNPE() { withUserData(null); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testWithUserDataEmpty() { withUserData("".getBytes()); } |
### Question:
RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions asType(String type) { formParameters.put("InstanceType", checkNotNull(type, "type")); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer:
@Test public void testWithInstanceType() { RunInstancesOptions options = new RunInstancesOptions(); options.asType(InstanceType.C1_XLARGE); assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); }
@Test public void testWithInstanceTypeStatic() { RunInstancesOptions options = asType(InstanceType.C1_XLARGE); assertEquals(options.buildFormParameters().get("InstanceType"), ImmutableList.of("c1.xlarge")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithInstanceTypeNPE() { asType(null); } |
### Question:
RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions withKernelId(String kernelId) { formParameters.put("KernelId", checkNotNull(kernelId, "kernelId")); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer:
@Test public void testWithKernelId() { RunInstancesOptions options = new RunInstancesOptions(); options.withKernelId("test"); assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); }
@Test public void testWithKernelIdStatic() { RunInstancesOptions options = withKernelId("test"); assertEquals(options.buildFormParameters().get("KernelId"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithKernelIdNPE() { withKernelId(null); } |
### Question:
RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions withRamdisk(String ramDiskId) { formParameters.put("RamdiskId", checkNotNull(ramDiskId, "ramDiskId")); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer:
@Test public void testWithRamdisk() { RunInstancesOptions options = new RunInstancesOptions(); options.withRamdisk("test"); assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); }
@Test public void testWithRamdiskStatic() { RunInstancesOptions options = withRamdisk("test"); assertEquals(options.buildFormParameters().get("RamdiskId"), ImmutableList.of("test")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithRamdiskNPE() { withRamdisk(null); } |
### Question:
DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds) { this.sshKeyIds = ImmutableSet.copyOf(checkNotNull(sshKeyIds, "sshKeyIds cannot be null")); return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); }### Answer:
@Test public void testSShKeyIds() { TemplateOptions options = new DigitalOcean2TemplateOptions().sshKeyIds(ImmutableSet.of(1, 2, 3)); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getSshKeyIds(), ImmutableSet.of(1, 2, 3)); } |
### Question:
RunInstancesOptions extends BaseEC2RequestOptions { public RunInstancesOptions withClientToken(String clientToken) { formParameters.put("ClientToken", checkNotNull(clientToken, "clientToken")); return this; } RunInstancesOptions withKeyName(String keyName); RunInstancesOptions withSecurityGroups(String... securityGroups); RunInstancesOptions withSecurityGroups(Iterable<String> securityGroups); RunInstancesOptions withSecurityGroup(String securityGroup); RunInstancesOptions withUserData(byte[] unencodedData); RunInstancesOptions asType(String type); RunInstancesOptions withKernelId(String kernelId); RunInstancesOptions withRamdisk(String ramDiskId); RunInstancesOptions withBlockDeviceMappings(Set<? extends BlockDeviceMapping> mappings); RunInstancesOptions withClientToken(String clientToken); static final RunInstancesOptions NONE; }### Answer:
@Test public void testWithClientToken() { RunInstancesOptions options = withClientToken("some-token"); assertEquals(options.buildFormParameters().get("ClientToken"), ImmutableList.of("some-token")); }
@Test(expectedExceptions = NullPointerException.class) public void testWithClientTokenNPE() { withClientToken(null); } |
### Question:
DigitalOcean2TemplateOptions extends TemplateOptions implements Cloneable { public DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking) { this.privateNetworking = privateNetworking; return this; } DigitalOcean2TemplateOptions privateNetworking(boolean privateNetworking); DigitalOcean2TemplateOptions backupsEnabled(boolean backupsEnabled); DigitalOcean2TemplateOptions sshKeyIds(Iterable<Integer> sshKeyIds); DigitalOcean2TemplateOptions autoCreateKeyPair(boolean autoCreateKeyPair); DigitalOcean2TemplateOptions userData(byte[] userData); @Deprecated @Override TemplateOptions userMetadata(Map<String, String> userMetadata); @Deprecated @Override TemplateOptions userMetadata(String key, String value); @Deprecated @Override Map<String, String> getUserMetadata(); Set<Integer> getSshKeyIds(); boolean getPrivateNetworking(); boolean getBackupsEnabled(); boolean getAutoCreateKeyPair(); byte[] getUserData(); @Override DigitalOcean2TemplateOptions clone(); @Override void copyTo(TemplateOptions to); @Override int hashCode(); @Override boolean equals(Object obj); @Override ToStringHelper string(); }### Answer:
@Test public void testPrivateNetworking() { TemplateOptions options = new DigitalOcean2TemplateOptions().privateNetworking(true); assertEquals(options.as(DigitalOcean2TemplateOptions.class).getPrivateNetworking(), true); } |
### Question:
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 { servoCommand=new AdaFruit(); LOG.info("using AdaFruit ServoCommand handling"); } catch (Exception e) { ErrorHandler.getInstance().handle(e); } break; default: servoCommand = new ServoBlaster(); } } engine = new Engine(this, new EngineMap(servoCommand)); steering = new Steering(this, new SteeringMap(servoCommand)); led = new Led(new LedMap(servoCommand)); } 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(); static Car getInstance(); static void resetInstance(); static ServoCommand servoCommand; }### Answer:
@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) servoCommand.showLog(); } |
### Question:
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 readInis); Configuration(); String getGraphFilePath(); void setGraphFilePath(String graphFilePath); void fromIni(); void addEnv(Environment env); TinkerGraph getGraph(); void setGraph(TinkerGraph graph); GraphTraversalSource g(); File getGraphFile(); void read(File graphFile); void write(File graphFile); String asString(); Map<String, Environment> getEnvironments(); Environment getEnvironmentFromVertex(Vertex v); void write(); static String STORE_MODE; static String STORE_EXTENSION; }### Answer:
@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(); } |
### Question:
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 asJsonObject(); static void from(JsonObject configJo); List<String> getMyIpAddresses(); String getString(String key); int getInteger(String key); double getDouble(String key); static void reset(); static void from(String propFilePath); static void mock(); static String dukesHome; public String propFilePath; }### Answer:
@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(env.isPi()); assertEquals(port, env.getInteger(Config.WEBCONTROL_PORT)); propFile.delete(); } |
### Question:
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.error("Error while determining IP addresses: ", e); return null; } } private Environment(); Environment(String propFilePath); static String readFirstLine(File file); static String osRelease(); boolean isPi(); static Environment getInstance(); boolean runningOnRaspberryPi(); Properties getProperties(); JsonObject asJsonObject(); static void from(JsonObject configJo); List<String> getMyIpAddresses(); String getString(String key); int getInteger(String key); double getDouble(String key); static void reset(); static void from(String propFilePath); static void mock(); static String dukesHome; public String propFilePath; }### Answer:
@Test public void testGetMyIpAddresses() { List<String> ips = Environment.getInstance().getMyIpAddresses(); assertNotNull(ips); assertTrue(ips.size() > 1); } |
### Question:
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 runningOnRaspberryPi(); Properties getProperties(); JsonObject asJsonObject(); static void from(JsonObject configJo); List<String> getMyIpAddresses(); String getString(String key); int getInteger(String key); double getDouble(String key); static void reset(); static void from(String propFilePath); static void mock(); static String dukesHome; public String propFilePath; }### Answer:
@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); } |
### Question:
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 RuntimeException( "vertx not available resultHandler result is null")); } this.deployVerticles(deploymentOptions, verticles); }); } else { this.deployVerticles(deploymentOptions, verticles); } } Vertx getVertx(); void prepare(); void configureCluster(String clusterHostname,String publicHost); void clusteredVertx(Handler<AsyncResult<Vertx>> resultHandler); DeploymentOptions getDeployMentOptions(boolean worker); void deployVerticles(AbstractVerticle... verticles); VertxOptions getOptions(); void undeployVerticle(DukesVerticle verticle); String getHostname(); void setHostname(String hostname); static final int MAX_START_TIME; }### Answer:
@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 (testVerticle.counter <=minLoops) { Thread.sleep(TestVerticle.TEST_INTERVAL_MS); } } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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(); }### Answer:
@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()); ROI rois[] = { new ROI("all", 0, 0, 1, 1), new ROI("far", 0, 0, 1, 0.5), new ROI("near", 0, 0.5, 1, 0.5), new ROI("left", 0, 0, 0.5, 1), new ROI("right", 0.5, 0, 0.5, 1) }; for (ROI roi : rois) { System.out.println(roi); Mat roiImage = roi.region(image); if (debug) System.out.println(String.format("%10s: %4d x %4d", roi.name, roiImage.width(), roiImage.height())); assertEquals(roiImage.width(), image.width() * roi.rw, 0.1); assertEquals(roiImage.height(), image.height() * roi.rh, 0.1); this.writeImage("dukes_roi_" + roi.name, roiImage); } } } |
### Question:
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 LaneDetectionResult fromJsonObject(JsonObject jo); boolean cmdOk(AngleRange angleRange, int minFound); void setTime(LaneDetectionResult ldr); void analyzeAngleRanges(int timeWindow, boolean showDebug); @Override JsonObject getNavigationInstruction(LaneDetectionResult ldr); JsonObject steerCommand(Double angle); @Override void navigateWithInstruction(JsonObject navigationInstruction); @Override void navigateWithMessage(Message<JsonObject> ldrMessage); @Override void navigateWithLaneDetectionResult(LaneDetectionResult ldr); @Override void videoStopped(VideoInfo videoInfo); static int COMMAND_LOOP_INTERVAL; static final int MAX_DURATION_NO_LINES_DETECTED; static final int DEFAULT_TIME_WINDOW; }### Answer:
@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 = nav.g().V().count().next().longValue(); assertEquals(3, nodeCount); } |
### Question:
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(timeWindow, showDebug); if (currentTime - startTime > MAX_DURATION_NO_LINES_DETECTED && stopRangeLeft.count + stopRangeRight.count == 0 || emergencyStopActivated) { this.emergencyStopActivated = true; return ActionVerticle.emergencyStopCommand(); } int MIN_FOUND_PER_TIMEWINDOW = 3; AngleRange navigateRange = null; if (middleRange.count >= MIN_FOUND_PER_TIMEWINDOW) { navigateRange = courseRange; } else { navigateRange = leftRange.count > rightRange.count ? leftRange : rightRange; } if (this.cmdOk(navigateRange, MIN_FOUND_PER_TIMEWINDOW)) { double angle = navigateRange.steer(); String msg = ldr.debugInfo() + String.format("\nsteer by %s: %s", navigateRange.name, Line.angleString(angle)); LOG.debug(msg); ldrVertex.property("steer",angle); ldrVertex.property("steerBy",navigateRange.name); ldrVertex.property("debugInfo",msg); tsLatestCommand = currentTime; message = steerCommand(angle); } return message; } StraightLaneNavigator(); StraightLaneNavigator(int timeWindow); DukesVerticle getSender(); void setSender(DukesVerticle sender); Vertex addToGraph(LaneDetectionResult ldr); @Override LaneDetectionResult fromJsonObject(JsonObject jo); boolean cmdOk(AngleRange angleRange, int minFound); void setTime(LaneDetectionResult ldr); void analyzeAngleRanges(int timeWindow, boolean showDebug); @Override JsonObject getNavigationInstruction(LaneDetectionResult ldr); JsonObject steerCommand(Double angle); @Override void navigateWithInstruction(JsonObject navigationInstruction); @Override void navigateWithMessage(Message<JsonObject> ldrMessage); @Override void navigateWithLaneDetectionResult(LaneDetectionResult ldr); @Override void videoStopped(VideoInfo videoInfo); static int COMMAND_LOOP_INTERVAL; static final int MAX_DURATION_NO_LINES_DETECTED; static final int DEFAULT_TIME_WINDOW; }### Answer:
@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.hasNext() && !imageFetcher.isClosed()) { Image image = imageFetcher.fetch(); frameIndex = image.getFrameIndex(); System.out.println(frameIndex); if (imageFetcher.hasNext()) { LaneDetector laneDetector = LaneDetector.getDefault(); LaneDetectionResult ldr = laneDetector.detect(image); if (debug) System.out.println(ldr.debugInfo()); JsonObject navJo = nav.getNavigationInstruction(ldr); if (navJo != null) System.out.println(navJo.encodePrettily()); } } imageFetcher.close(); long nodeCount = nav.g().V().count().next().longValue(); assertEquals(maxFrameIndex, nodeCount); } |
### Question:
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 car); @Override void start(); }### Answer:
@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(Config.WATCHDOG_MAX_MISSED_BEATS); assertEquals(2,maxMissedBeats); WatchDog watchDog=new WatchDog(car); clusterStarter.deployVerticles(watchDog); watchDog.waitStatus(Status.started,20000,10); Vertx vertx=clusterStarter.getVertx(); assertNotNull(vertx); assertEquals(watchDog.getVertx(),vertx); watchDog.send(Characters.FLASH,"type","heartbeat"); int loops=0; while(!car.powerIsOn() && loops<=100) { Thread.sleep(10); loops++; } assertTrue(loops<100); LOG.info(String.format("car powered on after %3d msecs",loops*10)); Thread.sleep(heartBeatInterval*(maxMissedBeats+3)); assertTrue(!car.powerIsOn()); } |
### Question:
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 getLed(); static Car getInstance(); static void resetInstance(); static ServoCommand servoCommand; }### Answer:
@Test public void testSteering() throws Exception { Car car = getCar(); Steering steering = car.getSteering(); steering.center(); ServoPosition cpos = steering.getSteeringMap().getCurrentPosition(); System.out.println(cpos); } |
### Question:
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(); static Car getInstance(); static void resetInstance(); static ServoCommand servoCommand; }### Answer:
@Test public void testLed() throws Exception { Car car = getCar(); Led led = car.getLed(); led.statusLedOn(); led.statusLedOff(); if (debug) servoCommand.showLog(); } |
### Question:
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 createNextImage(Mat frame, long currentMillis); Observable<Image> toObservable(); boolean hasNext(); boolean isClosed(); public boolean debug; static double DEFAULT_FPS; }### Answer:
@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); } assertEquals(488, imageFetcher.getFrameIndex()); } |
### Question:
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.this.fetch(); if (hasNext) { if (debug && frameIndex % Math.round(getFps()) == 0) { String msg = String.format("->%6d:%4.0fx%4.0f", frameIndex, size.width, size.height); LOG.info(msg); } observableEmitter.onNext(image); } } observableEmitter.onComplete(); } }); return observable; } 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 createNextImage(Mat frame, long currentMillis); Observable<Image> toObservable(); boolean hasNext(); boolean isClosed(); public boolean debug; static double DEFAULT_FPS; }### Answer:
@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); assertTrue(imageObserver.completed); assertEquals(768,imageObserver.cols); assertEquals(576,imageObserver.rows); }
@Test public void testImageFetcherObservableSample() { ImageFetcher imageFetcher = getTestImageFetcher(); Observable<Image> imageObservable = imageFetcher.toObservable(); ImageObserver imageObserver = new ImageObserver(); imageObserver.debug=debug; imageObservable.sample(40, TimeUnit.MILLISECONDS).subscribe(imageObserver); assertNull(imageObserver.error); assertTrue(imageObserver.completed); assertEquals(768,imageObserver.cols); assertEquals(576,imageObserver.rows); } |
### Question:
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; }### Answer:
@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_START_TIME, 10); JsonObject configJo=Config.getEnvironment().asJsonObject(); remoteCar.send(Characters.GENERAL_LEE,configJo); Thread.sleep(ClusterStarter.MAX_START_TIME); } |
### Question:
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 = { "--publichost" }, usage = "hostname") String publicHost; }### Answer:
@Test public void testRemoteCarCommandLine() { Environment.mock(); String args[]= {}; RemoteCar.main(args); } |
### Question:
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); }### Answer:
@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("corners: "); String delim = ""; for (int i = 0; i < 4; i++) { System.out.print( String.format("(%.1f,%.1f)%s", corners[i].x, corners[i].y, delim)); delim = ","; if (i == 2) delim = "\n"; } } writeImage("chessBoardCorners", chessboard); Size size = chessboard.size(); Polygon imagePolygon = new ImagePolygon(size, 0, 0, 1, 0, 1, 1, 0, 1); Polygon worldPolygon = new ImagePolygon(corners); PerspectiveShift perspectiveShift = new PerspectiveShift(imagePolygon, worldPolygon); if (debug) { System.out.println("image: " + perspectiveShift.imagePoints); System.out.println("world: " + perspectiveShift.worldPoints); } Mat shifted = perspectiveShift.apply(chessboard); writeImage("shiftedChessBoard", shifted); }
@Test public void testTransform() throws Exception { Mat original = Imgcodecs.imread(testPath + "dukes_livingroom.jpeg"); ROI roi = new ROI("near", 0, 0.4, 1, 0.6); Mat image = roi.region(original); Polygon imagePolygon = new ImagePolygon(image.size(), 0, 0, 1, 0, 1, 1, 0, 1); Polygon worldPolygon = new ImagePolygon(image.size(), 0.30, 0.20, 0.80, 0.28, 0.96, 0.62, 0.15, 0.46); PerspectiveShift perspectiveShift = new PerspectiveShift(imagePolygon, worldPolygon); Mat shifted = perspectiveShift.apply(image); if (debug) { System.out.println("worldp:" + perspectiveShift.worldPolygon); System.out.println("world: " + perspectiveShift.worldPoints); writeImage("roiImage", image); writeImage("shiftedImage", shifted); } } |
### Question:
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.subtract(BigInteger.ONE)), dInt = eInt.modInverse(mInt), dPInt = dInt.remainder(pInt.subtract(BigInteger.ONE)), dQInt = dInt.remainder(qInt.subtract(BigInteger.ONE)), qInvInt = qInt.modInverse(pInt); final byte[] n = BigIntegers.asUnsignedByteArray(nInt), d = BigIntegers.asUnsignedByteArray(dInt), dP = BigIntegers.asUnsignedByteArray(dPInt), dQ = BigIntegers.asUnsignedByteArray(dQInt), qInv = BigIntegers.asUnsignedByteArray(qInvInt); return new RSAKeyPair(n, e, d, p, q, dP, dQ, qInv); } RSAKeyPair(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q, byte[] dP, byte[] dQ, byte[] qInv); static RSAKeyPair fromExponents(byte[] e, byte[] p, byte[] q); final byte[] n; final byte[] e; final byte[] d; final byte[] p; final byte[] q; final byte[] dP; final byte[] dQ; final byte[] qInv; }### Answer:
@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(rsaPair.q, rsaSpec.q); assertArrayEquals(rsaPair.dP, rsaSpec.dP); assertArrayEquals(rsaPair.dQ, rsaSpec.dQ); assertArrayEquals(rsaPair.qInv, rsaSpec.qInv); } |
### Question:
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.keyParameters.getModulus())); put("e", BigIntegers.asUnsignedByteArray(state.keyParameters.getExponent())); if (!state.mgf1HashType.equals(DEFAULT_MGF1_HASH)) { put("mgf1Hash", state.mgf1HashType.getAlgorithmName()); } }}); } } RSAOAEPPublicKey(); RSAOAEPPublicKey(byte[] n, byte[] e, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override boolean canEncrypt(); @Override int getBitStrength(); @Override boolean isInitialized(); @NonNull @Override byte[] encrypt(byte[] plaintext); @NonNull @Override boolean checkSignature(InputStream input, byte[] signature, HashType hashType, int saltLength); @NonNull @Override String algorithmTag(); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; }### Answer:
@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 goodPublicKey1 = new RSAOAEPPublicKey( BigIntegers.asUnsignedByteArray(randomPublicKey1.getModulus()), BigIntegers.asUnsignedByteArray(randomPublicKey1.getExponent()), HashType.SHA512, HashType.SHA512, new SecureRandom()); Map map1 = goodPublicKey1.toHash(); assertArrayEquals((byte[]) map1.get("n"), BigIntegers.asUnsignedByteArray(randomPublicKey1.getModulus())); assertArrayEquals((byte[]) map1.get("e"), BigIntegers.asUnsignedByteArray(randomPublicKey1.getExponent())); assertEquals(map1.get("mgf1Hash"), "SHA-512"); }
@Test public void toHashWithDefaultData() throws Exception { AbstractPublicKey goodPublicKey1 = new RSAOAEPPublicKey( BigIntegers.asUnsignedByteArray(randomPublicKey1.getModulus()), BigIntegers.asUnsignedByteArray(randomPublicKey1.getExponent()), HashType.SHA1, HashType.SHA1, new SecureRandom()); Map map1 = goodPublicKey1.toHash(); assertArrayEquals((byte[]) map1.get("n"), BigIntegers.asUnsignedByteArray(randomPublicKey1.getModulus())); assertArrayEquals((byte[]) map1.get("e"), BigIntegers.asUnsignedByteArray(randomPublicKey1.getExponent())); assertFalse(map1.containsKey("hash")); assertFalse(map1.containsKey("mgf1Hash")); } |
### Question:
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 itemId, ItemResult result); void idsCheck(HashId itemId); int size(); }### Answer:
@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())); } |
### Question:
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(printStream); try { block.call(); } finally { System.setOut(oldStream); System.setErr(oldErr); } return bos.toString(); } static String copyOut(Block block); }### Answer:
@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.print("hello"); System.out.println(" world!"); }); assertEquals("hello world!\n", result); result = ConsoleInterceptor.copyOut( () ->{ System.out.print(58387); System.out.println(" world!"); }); assertEquals("58387 world!\n", result); } |
### Question:
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 getString(String key, String defaultValue); String getString(String key); byte[] getBinary(String key); @NonNull byte[] getBinaryOrThrow(String key); @Deprecated boolean getBoolean(String key); Boolean getBoolean(String key, Boolean defaultValue); Boolean getBooleanOrThrow(String key); @Deprecated Binder of(String key); static Binder of(String key, Object value, Object... keysValues); Binder getOrCreateBinder(String key); Binder getBinder(String key); Binder getBinderOrThrow(String key); Binder getBinder(String key, Binder defaultValue); @Deprecated int getInt(String key); int getIntOrThrow(String key); @Deprecated long getLong(String key); long getLong(String key, long defaultValue); Integer getInt(String key, Integer defaultValue); ArrayList<?> getArray(String key); ArrayList<Binder> getBinders(String key); T set(String key, T object); Binder unmodifiableCopy(); void freeze(); static Binder from(Object x); static T convertAllMapsToBinders(Object object); static Binder of(Object x); Binder putAll(String key, Object value, Object... keyValuePairs); ZonedDateTime getZonedDateTime(String key, ZonedDateTime defaultValue); ZonedDateTime getZonedDateTimeOrThrow(String key); long getLongOrThrow(String key); Bytes getBytesOrThrow(String key); T getOrThrow(String key); List<T> getOrCreateList(String key); List<T> getList(String key, List<T> defaultValue); List getListOrThrow(String key); int addToInt(String name, int delta); Binder getBinderOrThrow(String... path); String getStringOrThrow(String... path); T getOrThrow(String... path); T getOrNull(String... path); static final Binder EMPTY; }### Answer:
@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()); assertEquals("bar", b.getBinder("inner").get("foo")); Binder e = Binder.EMPTY; assertTrue(e.isFrozen()); x = new Binder(); assertEquals(e, x); assertFalse(b.equals(e)); } |
### Question:
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 getStringOrThrow(String key); String getString(String key, String defaultValue); String getString(String key); byte[] getBinary(String key); @NonNull byte[] getBinaryOrThrow(String key); @Deprecated boolean getBoolean(String key); Boolean getBoolean(String key, Boolean defaultValue); Boolean getBooleanOrThrow(String key); @Deprecated Binder of(String key); static Binder of(String key, Object value, Object... keysValues); Binder getOrCreateBinder(String key); Binder getBinder(String key); Binder getBinderOrThrow(String key); Binder getBinder(String key, Binder defaultValue); @Deprecated int getInt(String key); int getIntOrThrow(String key); @Deprecated long getLong(String key); long getLong(String key, long defaultValue); Integer getInt(String key, Integer defaultValue); ArrayList<?> getArray(String key); ArrayList<Binder> getBinders(String key); T set(String key, T object); Binder unmodifiableCopy(); void freeze(); static Binder from(Object x); static T convertAllMapsToBinders(Object object); static Binder of(Object x); Binder putAll(String key, Object value, Object... keyValuePairs); ZonedDateTime getZonedDateTime(String key, ZonedDateTime defaultValue); ZonedDateTime getZonedDateTimeOrThrow(String key); long getLongOrThrow(String key); Bytes getBytesOrThrow(String key); T getOrThrow(String key); List<T> getOrCreateList(String key); List<T> getList(String key, List<T> defaultValue); List getListOrThrow(String key); int addToInt(String name, int delta); Binder getBinderOrThrow(String... path); String getStringOrThrow(String... path); T getOrThrow(String... path); T getOrNull(String... path); static final Binder EMPTY; }### Answer:
@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")); assertEquals(1505774997427L, b.getLongOrThrow("l1")); assertEquals(1505774997427L, b.getLongOrThrow("l2")); } |
### Question:
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(InputStream input, byte[] signature, HashType hashType); boolean verify(byte[] input, byte[] signature, HashType hashType); boolean verify(String input, byte[] signature, HashType hashType); KeyInfo info(); byte[] packedInfo(); byte[] pack(); String packToBase64String(); void unpack(byte[] bytes); boolean canSign(); boolean isPublic(); boolean isPrivate(); AbstractKey getPublicKey(); @Override final Binder toBinder(); @Override final T updateFrom(Binder source); static AbstractKey fromBinder(Binder binder); boolean matchType(AbstractKey other); boolean matchTag(AbstractKey other); void setTag(String tag); void setTag(byte[] tag); @Override String toString(); Capsule.KeySource asKeySource(); byte[] fingerprint(); Digest updateDigestWithKeyComponents(Digest digest); byte[] createAnonymousId(); boolean matchAnonymousId(@NonNull byte[] packedId); KeyAddress address(boolean useSha3_384, int keyMark); final KeyAddress getShortAddress(); final KeyAddress getLongAddress(); @Override boolean isMatchingKey(AbstractKey key); @Override final boolean isMatchingKeyAddress(KeyAddress other); static final int FINGERPRINT_SHA256; static final int FINGERPRINT_SHA384; static final int TYPE_PRIVATE; static final int TYPE_PUBLIC; static final int TYPE_PRIVATE_PASSWORD; static final int TYPE_PRIVATE_PASSWORD_V2; }### Answer:
@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]); } |
### Question:
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(); }### Answer:
@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); } |
### Question:
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(); }### Answer:
@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 = new AtomicInteger(0); RunnableWithDynamicPeriod r = new RunnableWithDynamicPeriod(() -> { long t1 = System.nanoTime(); long dt = (t1 - time) / 1000000; time = t1; long dt0 = periods.get(Math.min(iTick.get(), periods.size()-1)); System.out.println("tick "+iTick.get()+": " + dt + "ms, must be " + dt0 + "ms"); if (!(Math.abs(dt0 - dt) < 5+dt0/10)) errorsCount.incrementAndGet(); iTick.incrementAndGet(); }, periods, executorService); r.run(); Thread.sleep(8500); r.restart(); iTick.set(0); time = System.nanoTime(); Thread.sleep(10000); System.out.println("executorService.size: " + executorService.getQueue().size()); Assert.assertEquals(1, executorService.getQueue().size()); r.cancel(true); while (executorService.getQueue().size() > 0) { Thread.sleep(1000); System.out.println("executorService.size: " + executorService.getQueue().size()); } Assert.assertEquals(0, executorService.getQueue().size()); Assert.assertEquals(0, errorsCount.get()); } |
### Question:
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(); }### Answer:
@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); RunnableWithDynamicPeriod r = new RunnableWithDynamicPeriod(() -> { long t1 = System.nanoTime(); long dt = (t1 - time) / 1000000; time = t1; long dt0 = periods.get(Math.min(iTick.get(), periods.size()-1)); System.out.println("tick: " + dt + "ms, must be " + dt0 + "ms"); if (!(Math.abs(dt0 - dt) < dt0/10)) errorsCount.incrementAndGet(); iTick.incrementAndGet(); }, periods, executorService); r.run(); System.out.println("wait for ticks"); Thread.sleep(2000); AtomicInteger ticksCount = new AtomicInteger(iTick.get()); System.out.println("now cancel"); r.cancel(true); Thread.sleep(2000); Assert.assertEquals(ticksCount.get(), iTick.get()); } |
### Question:
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 (toIndex < fromIndex) { int t = fromIndex; fromIndex = toIndex; toIndex = t; } int length = copy.size(); if (fromIndex < 0) fromIndex = 0; if (toIndex >= length) toIndex = length; if (fromIndex >= length || toIndex < 1 || fromIndex == toIndex) return Collections.emptyList(); return copy.subList(fromIndex, toIndex); } BufferedLogger(int maxEntries); void e(String s); void flush(); boolean flush(long millis); PrintStream printTo(PrintStream ps, boolean printTimestamp); @NonNull Entry log(String message); @NonNull Entry d(String message); @NonNull List<Entry> getLast(int maxEntries); List<Entry> slice(long id, int maxEntries); void clear(); List<Entry> getCopy(); void interceptStdOut(); @Override void close(); void stopInterceptingStdOut(); }### Answer:
@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("line 6,line 7,line 8", result); result = str(log.slice(all.get(5).id, -3)); assertEquals("line 2,line 3,line 4", result); result = str(log.slice(all.get(2).id, -3)); assertEquals("line 0,line 1", result); result = str(log.slice(all.get(8).id, +3)); assertEquals("line 9", result); result = str(log.slice(all.get(0).id, 20)); assertEquals("line 1,line 2,line 3,line 4,line 5,line 6,line 7,line 8,line 9", result); result = str(log.slice(all.get(9).id, -20)); assertEquals("line 0,line 1,line 2,line 3,line 4,line 5,line 6,line 7,line 8", result); result = str(log.slice(all.get(0).id-1, 20)); assertEquals("line 0,line 1,line 2,line 3,line 4,line 5,line 6,line 7,line 8,line 9", result); } |
### Question:
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 Entry log(String message); @NonNull Entry d(String message); @NonNull List<Entry> getLast(int maxEntries); List<Entry> slice(long id, int maxEntries); void clear(); List<Entry> getCopy(); void interceptStdOut(); @Override void close(); void stopInterceptingStdOut(); }### Answer:
@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())); } |
### Question:
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 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 SecureRandom getRng(); static int randomInt(int max); static byte[] randomBytes(int length); static byte[] randomNegativeBytes(int length); static int randomIntInRange(int inclusiveMinimum, int inclusiveMaximum); static byte[] read(File f); static void waitFor(Supplier<Boolean> function); static void delay(long millis, Action action); static void later(Action action); static HashMap<String, Object> map(Object... args); static Collection<T> collection(Object x); static ArrayList<T> list(U x); static ArrayList<T> listOf(U... objects); static boolean deepEqualityTest(Object a, Object b); static byte[] decodeBase64(String base64); static DeferredResult inParallel(final Task task); static DeferredResult inParallel(final TaskWithoutResult task); static String bytesToHex(byte[] bytes); static String snakeToCamelCase(String snakeString); }### Answer:
@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")); } |
### Question:
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[] read(InputStream inputStream); static String readToString(InputStream inputStream); static A checkSame(A oldValue, B newValue, Runnable onChanged); static T sample(Collection source); static SecureRandom getRng(); static int randomInt(int max); static byte[] randomBytes(int length); static byte[] randomNegativeBytes(int length); static int randomIntInRange(int inclusiveMinimum, int inclusiveMaximum); static byte[] read(File f); static void waitFor(Supplier<Boolean> function); static void delay(long millis, Action action); static void later(Action action); static HashMap<String, Object> map(Object... args); static Collection<T> collection(Object x); static ArrayList<T> list(U x); static ArrayList<T> listOf(U... objects); static boolean deepEqualityTest(Object a, Object b); static byte[] decodeBase64(String base64); static DeferredResult inParallel(final Task task); static DeferredResult inParallel(final TaskWithoutResult task); static String bytesToHex(byte[] bytes); static String snakeToCamelCase(String snakeString); }### Answer:
@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; i++) { y.add(Do.sample(x)); t.add(Do.sample(z)); } assertEquals(y,x); } |
### Question:
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 SecureRandom getRng(); static int randomInt(int max); static byte[] randomBytes(int length); static byte[] randomNegativeBytes(int length); static int randomIntInRange(int inclusiveMinimum, int inclusiveMaximum); static byte[] read(File f); static void waitFor(Supplier<Boolean> function); static void delay(long millis, Action action); static void later(Action action); static HashMap<String, Object> map(Object... args); static Collection<T> collection(Object x); static ArrayList<T> list(U x); static ArrayList<T> listOf(U... objects); static boolean deepEqualityTest(Object a, Object b); static byte[] decodeBase64(String base64); static DeferredResult inParallel(final Task task); static DeferredResult inParallel(final TaskWithoutResult task); static String bytesToHex(byte[] bytes); static String snakeToCamelCase(String snakeString); }### Answer:
@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, is(lessThan(20))); assertThat(max, is(greaterThan(80))); } |
### Question:
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 sendSuccess(Object data); void sendFailure(Object data); boolean isDone(); @SuppressWarnings("unchecked") T getResult(); T waitSuccess(); T await(); T await(long millis); final DeferredResult join(); boolean isSuccess(); final boolean join(long millis); }### Answer:
@Test public void success() throws Exception { DeferredResult dr = new DeferredResult(); dr.success( (text-> assertEquals("hello", text))); dr.sendSuccess("hello"); } |
### Question:
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(); @Deprecated T waitFired(); T await(); T await(long milliseconds); final void fire(); }### Answer:
@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(); }); event.fire(11); int res = event.waitFired(); assertEquals(11, res); latch.await(); assertEquals(11, values[0]); assertEquals(11, values[1]); } } |
### Question:
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(), idDigest); } byte[] encrypt(byte[] plain); byte[] decrypt(byte[] plain); byte[] sign(InputStream input, HashType hashType); byte[] sign(byte[] input, HashType hashType); boolean verify(InputStream input, byte[] signature, HashType hashType); boolean verify(byte[] input, byte[] signature, HashType hashType); boolean verify(String input, byte[] signature, HashType hashType); KeyInfo info(); byte[] packedInfo(); byte[] pack(); String packToBase64String(); void unpack(byte[] bytes); boolean canSign(); boolean isPublic(); boolean isPrivate(); AbstractKey getPublicKey(); @Override final Binder toBinder(); @Override final T updateFrom(Binder source); static AbstractKey fromBinder(Binder binder); boolean matchType(AbstractKey other); boolean matchTag(AbstractKey other); void setTag(String tag); void setTag(byte[] tag); @Override String toString(); Capsule.KeySource asKeySource(); byte[] fingerprint(); Digest updateDigestWithKeyComponents(Digest digest); byte[] createAnonymousId(); boolean matchAnonymousId(@NonNull byte[] packedId); KeyAddress address(boolean useSha3_384, int keyMark); final KeyAddress getShortAddress(); final KeyAddress getLongAddress(); @Override boolean isMatchingKey(AbstractKey key); @Override final boolean isMatchingKeyAddress(KeyAddress other); static final int FINGERPRINT_SHA256; static final int FINGERPRINT_SHA384; static final int TYPE_PRIVATE; static final int TYPE_PUBLIC; static final int TYPE_PRIVATE_PASSWORD; static final int TYPE_PRIVATE_PASSWORD_V2; }### Answer:
@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); assertEquals(64, id2.length); assertFalse(Arrays.equals(id1, id12)); assertFalse(Arrays.equals(id1, id2)); assertFalse(Arrays.equals(id12, id2)); assertTrue(k1.matchAnonymousId(id1)); assertTrue(k1.matchAnonymousId(id12)); assertTrue(k2.matchAnonymousId(id2)); assertFalse(k2.matchAnonymousId(id1)); assertFalse(k2.matchAnonymousId(id12)); assertFalse(k1.matchAnonymousId(id2)); } |
### Question:
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); @Override Map<String, Object> receive(); }### Answer:
@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")); }
@Test public void directLoadTest() throws Exception { StreamConnector sa = new StreamConnector(); StreamConnector sb = new StreamConnector(); Farcall fa = new Farcall(new BossConnector(sa.getInputStream(), sb.getOutputStream())); Farcall fb = new Farcall(new BossConnector(sb.getInputStream(), sa.getOutputStream())); int [] counts = new int[2]; fa.start(command -> { if (command.getName().equals("fast")) { counts[0]++; return "fast done"; } else if (command.getName().equals("slow")) { Thread.sleep(3); counts[1]++; return "slow done"; } return null; }); fb.start(); ExecutorService es = Executors.newWorkStealingPool(); ArrayList<Long> times = new ArrayList<>(); for( int rep=0; rep < 7; rep++ ) { ArrayList<Future<?>> futures = new ArrayList<>(); counts[0] = counts[1] = 0; long t = StopWatch.measure(() -> { CompletableFuture<?> cf = new CompletableFuture<>(); for (int r = 0; r < 40; r++) { futures.add(es.submit(() -> { for (int i = 0; i < 10; i++) assertEquals("fast done", fb.send("fast").waitSuccess()); return null; })); futures.add(es.submit(() -> { for (int i = 0; i < 2; i++) assertEquals("slow done", fb.send("slow").waitSuccess()); return null; })); } futures.forEach(f -> { try { f.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } }); }); times.add(t); } long t1 = times.get(2); long t2 = times.get(times.size()-1); long mean = (t1 + t2)/2; assertThat((double) Math.abs(t2-t1) / ((double) mean), CoreMatchers.is(lessThan(0.16)) ); } |
### Question:
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(Map<String, Object> data); @Override Map<String, Object> receive(); }### Answer:
@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.get("hello")); } |
### Question:
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 instanceof Collection) { return (T) ((Collection) x).stream() .map(i -> serialize(i, serializer)) .collect(Collectors.toList()); } String canonicalName = klass.getCanonicalName(); BiAdapter adapter = adapters.get(canonicalName); if (adapter == null) { if (x instanceof Map) { Binder serialized = new Binder(); ((Map)x).forEach((k,v) -> serialized.put(serialize(k),serialize(v))); return (T)serialized; } return (T) x; } Binder result = adapter.serialize(x, serializer); String tn = adapter.typeName(); result.put("__type", tn != null ? tn : canonicalName); return (T) result; } BiMapper(); BiMapper(BiMapper parent); void deserializeInPlace(Map map, BiDeserializer deserializer); T deserialize(Map map, BiDeserializer deserializer); T deserialize(Map map); T deserializeObject(Object x); T deserializeObject(Object obj, BiDeserializer deserializer); @NonNull T serialize(Object x, BiSerializer serializer); @NonNull T serialize(Object x); void registerAdapter(Class<T> klass, BiAdapter adapter); boolean unregister(Class klass); void registerClass(Class<? extends BiSerializable> klass); BiSerializer newSerializer(); BiDeserializer newDeserializer(); }### Answer:
@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.deserialize(res); assertEquals(now.truncatedTo(ChronoUnit.SECONDS), restored.get("time")); assertEquals(now.truncatedTo(ChronoUnit.SECONDS), DefaultBiMapper.deserialize(DefaultBiMapper.serialize(now))); } |
### Question:
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 listener); void post(Object event); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); }### Answer:
@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.stringCalls); assertEquals(2, Receiver2.objectCalls); assertEquals("test1", receiver.lastObject); assertEquals(0, Receiver2.lostCount); } |
### Question:
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); void postAfter(final Object event, final long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); }### Answer:
@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); } |
### Question:
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(Object subscriber); void register(Object subscriber, boolean registerWeak); }### Answer:
@Test public void testRegisterWeak() throws Exception { assertEquals(0, Receiver1.lostCount); informer.registerWeak(new Receiver1()); System.gc(); informer.post(11); assertEquals(0, Receiver1.lostCount); } |
### Question:
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(Object subscriber); void register(Object subscriber, boolean registerWeak); }### Answer:
@Test public void testRegisterStrong() throws Exception { assertEquals(0, Receiver1.lostCount); informer.registerStrong(new Receiver1()); informer.post(11); assertEquals(1, Receiver1.lostCount); } |
### Question:
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 long millis); void registerWeak(Object subscriber); void registerStrong(Object subscriber); boolean unregister(Object subscriber); void register(Object subscriber, boolean registerWeak); }### Answer:
@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, Receiver1.lostCount); } |
### Question:
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; while (startAt < input.length) { byte mod = divmod58(input, startAt); if (input[startAt] == 0) { ++startAt; } temp[--j] = (byte) ALPHABET[mod]; } while (j < temp.length && temp[j] == ALPHABET[0]) { ++j; } while (--zeroCount >= 0) { temp[--j] = (byte) ALPHABET[0]; } byte[] output = copyOfRange(temp, j, temp.length); return new String(output); } static String encode(byte[] input); static byte[] decode(String input); static byte[] decode(String input, boolean strict); }### Answer:
@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))); } } |
### Question:
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 typeMark, boolean useSha3_384); KeyAddress(byte[] packedSource); KeyAddress(String packedString); KeyAddress(Binder binder); @Override boolean isMatchingKey(AbstractKey key); @Override boolean isMatchingKeyAddress(KeyAddress other); final boolean isLong(); final byte[] getPacked(); final int getTypeMark(); @Override String toString(); @Override int hashCode(); @Override boolean equals(Object obj); static BiAdapter getBiAdapter(); }### Answer:
@Test public void isMatchingKey() throws KeyAddress.IllegalAddressException { testMatch(true); testMatch(false); } |
### Question:
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); }### Answer:
@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")); } |
### Question:
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_key.pub"; } } Role role = contract.getRole(roleName); if (role != null) { Set<PublicKey> keys = role.getKeys(); int index = 0; byte[] data; for (PublicKey key : keys) { index++; data = key.pack(); String name = fileName.replaceAll("\\.(pub)$", "_key_" + roleName + "_" + index + ".public.unikey"); if (base64) { name += ".txt"; } try (FileOutputStream fs = new FileOutputStream(name)) { if (base64) fs.write(Base64.encodeLines(data).getBytes()); else fs.write(data); fs.close(); } } report(roleName + " export public keys ok"); } else { addError(Errors.NOT_FOUND.name(), roleName, "role doesn't exist"); } } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; }### Answer:
@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()); } |
### Question:
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 void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; }### Answer:
@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()); } |
### Question:
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(Algorythm algorythm, byte[] tag, int keyLength); KeyInfo(Algorythm algorythm, byte[] tag); KeyInfo(PRF PRF, int rounds, byte[] salt, byte[] tag); KeyInfo(byte[] packedInfo); byte[] getSalt(); boolean matchType(KeyInfo otherInfo); boolean matchType(AbstractKey otherKey); boolean matchTag(KeyInfo keyInfo); void setTag(byte[] tag); String getBase64Tag(); boolean isPassword(); byte[] getTag(); int getRounds(); Algorythm getAlgorythm(); PRF getPRF(); int getKeyLength(); byte[] pack(); SymmetricKey derivePassword(String password); AbstractKey unpackKey(byte[] data); @Override String toString(); }### Answer:
@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.privateKey(2); kx = AbstractKey.fromBinder(k1.toBinder()); assertEquals(k1, kx); } |
### Question:
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(tc, u, amount, uKeys, withTestPayment); if (parcel != null) registerParcel(parcel, 0); return parcel; } static void main(String[] args); static PrivateKey getPrivateKey(); static BasicHttpClientSession getSession(int nodeNumber); static void breakSession(int nodeNumber); static void clearSession(); static void clearSession(boolean full); static void saveSession(); static void setVerboseMode(boolean verboseMode); static Contract loadContract(String fileName, Boolean fromPackedTransaction); static Parcel loadParcel(String fileName); static Contract loadContract(String fileName); static void exportContract(Contract contract, String fileName, String format, Boolean jsonPretty); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners); static boolean saveContract(Contract contract, String fileName, Boolean fromPackedTransaction, Boolean addSigners, Set<Contract> referencedItems); static boolean saveParcel(Parcel parcel, String fileName); static void saveContract(Contract contract, String fileName); static List<Wallet> findWallets(String path); static HashMap<String, Contract> findContracts(String path); static HashMap<String, Contract> findContracts(String path, Boolean recursively); static List<File> findFiles(String path, Boolean recursively); static Contract downloadContract(String url); static Parcel revokeContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment, PrivateKey... key); @Deprecated static Contract revokeContract(Contract contract, PrivateKey... key); @Deprecated static void registerContract(Contract contract, int waitTime, Boolean fromPackedTransaction); static Parcel prepareForRegisterContract(Contract contract, Contract u, int amount, Set<PrivateKey> uKeys, boolean withTestPayment); static Parcel prepareForRegisterPayingParcel(Contract contract, Contract u, int amount, int amountStorage, Set<PrivateKey> uKeys, boolean withTestPayment); static ItemResult registerParcel(Parcel parcel, int waitTime); static void registerContract(Contract contract); static void registerContract(Contract contract, int waitTime); static void setTestMode(); static void setTestRootPath(String rootPath); static void setNodeNumber(int number); static void setNodeUrl(String url); static void setTopologyFileName(String filename); static void setPrivateKey(PrivateKey key); static Reporter getReporter(); static synchronized ClientNetwork getClientNetwork(); static synchronized Map<String, PrivateKey> keysMap(); static synchronized Map<String, PrivateKey> keysMapContract(); static String DEFAULT_WALLET_PATH; static final String AMOUNT_FIELD_NAME; }### Answer:
@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.loadContract(contractFileName); System.out.println("contract: " + c.getId().toBase64String()); Thread.sleep(1500); System.out.println("probe before revoke"); callMain2("--probe", c.getId().toBase64String(), "--verbose"); Thread.sleep(500); uContract = getApprovedUContract(); callMain2("-revoke", contractFileName, "-k", PRIVATE_KEY_PATH, "-v", "--u", uContract, "-k", rootPath + "keys/stepan_mamontov.private.unikey"); Thread.sleep(2500); System.out.println("probe after revoke"); callMain("--probe", c.getId().toBase64String(), "--verbose"); System.out.println(output); assertEquals(0, errors.size()); assertTrue (output.indexOf(ItemState.REVOKED.name()) >= 0); } |
### Question:
Syntex1 extends Digest { @Override public int getLength() { return 36; } @Override int getLength(); }### Answer:
@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); assertThat( d3, equalTo(d1)); assertThat( d2, not(equalTo(d1))); InputStream in = new ByteArrayInputStream("Hello world".getBytes()); assertThat(d1, equalTo( new Syntex1().digest(in))); } |
### Question:
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); PrivateKey(int bitStrength); PrivateKey(); @Override boolean canSign(); @Override boolean isPrivate(); @Override byte[] decrypt(final byte[] encrypted); PublicKey getPublicKey(); byte[] pack(); @Override byte[] sign(InputStream input, HashType hashType); @Override KeyInfo info(); @Override boolean equals(Object obj); @Override int hashCode(); @Override byte[] fingerprint(); static PrivateKey fromPath(Path path); @Override Digest updateDigestWithKeyComponents(Digest digest); byte[] packWithPassword(String password); byte[] packWithPassword(String password, int rounds); static PrivateKey unpackWithPassword(byte[] packedBinary, String password); }### Answer:
@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.binaryKeys[3]); PrivateKey privateKey = new PrivateKey(packedPrivateKey); byte[] packedPrivateKey2 = privateKey.pack(); assertArrayEquals(packedPrivateKey, packedPrivateKey2); } |
### Question:
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 EncryptionError("decrypt failed", e); } } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; }### Answer:
@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) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); AbstractPrivateKey randomPrivateKey = randomPrivateKey4096; AbstractPublicKey randomPublicKey = randomPrivateKey.getPublicKey(); SecureRandom rng = new SecureRandom(); int maxMessageSize = ((RSAOAEPPrivateKey) randomPrivateKey).getMaxBlockSize(), minMessageSize = maxMessageSize, messageSize = (maxMessageSize >= minMessageSize) ? rng.nextInt(maxMessageSize - minMessageSize + 1) + minMessageSize : 0; for (int i = 0; i < NUMBER_OF_RANDOM_ENCRYPTION_DECRYPTION_CYCLES; i++) { ((RSAOAEPPrivateKey) randomPrivateKey).resetDecryptor(); ((RSAOAEPPublicKey) randomPublicKey).resetEncryptor(); byte[] message = new byte[messageSize]; rng.nextBytes(message); byte[] encrypted = randomPublicKey.encrypt(message), decrypted = randomPrivateKey.decrypt(encrypted); assertArrayEquals(decrypted, message); } } |
### Question:
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,
int dkLen); static byte[] derive(Class<? extends Digest> hash, String password, byte[] salt, int c, int dkLen); }### Answer:
@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]); byte[] DK = Do.decodeBase64(parts[6]); assertArrayEquals(DK, PBKDF2.derive(Sha512.class, password, salt, c, dkLen)); }
@Test public void computeSha1() throws Exception { String P = "password"; byte[] S = "salt".getBytes(); int c = 1; int dkLen = 20; byte[] DK = Hex.decode("0c 60 c8 0f 96 1f 0e 71\n" + "f3 a9 b5 24 af 60 12 06\n" + "2f e0 37 a6"); final byte[] key = PBKDF2.derive(Sha1.class, P, S, c, dkLen); assertArrayEquals(DK, key); }
@Test public void computeSha256() throws Exception { String P = "password"; byte[] S = "salt".getBytes(); int c = 1; int dkLen = 32; byte [] DK = Hex.decode("12 0f b6 cf fc f8 b3 2c\n" + "43 e7 22 52 56 c4 f8 37\n" + "a8 65 48 c9 2c cc 35 48\n" + "08 05 98 7c b7 0b e1 7b"); byte[] key = PBKDF2.derive(Sha256.class, P, S, c, dkLen); assertArrayEquals(DK, key); c = 2; DK = Hex.decode("ae 4d 0c 95 af 6b 46 d3\n" + " 2d 0a df f9 28 f0 6d d0\n" + " 2a 30 3f 8e f3 c2 51 df\n" + " d6 e2 d8 5a 95 47 4c 43"); c = 4096; DK = Hex.decode("c5 e4 78 d5 92 88 c8 41\n" + " aa 53 0d b6 84 5c 4c 8d\n" + " 96 28 93 a0 01 ce 4e 11\n" + " a4 96 38 73 aa 98 13 4a"); key = PBKDF2.derive(Sha256.class, P, S, c, dkLen); assertArrayEquals(DK, key); } |
### Question:
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 result.add(k); } } return result; } @Override Binder toBinder(); static KeyRing fromBinder(Binder source); @Override KeyRing updateFrom(Binder source); void clear(); void addKey(AbstractKey key); boolean removeKey(AbstractKey key); @Override @NonNull Collection<AbstractKey> findKey(KeyInfo keyInfo); void addKeys(AbstractKey... newKeys); @Override boolean equals(Object obj); @Override String toString(); boolean contains(AbstractKey k); }### Answer:
@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(), pk2.info().getTag()); KeyRing kr = new KeyRing(); SymmetricKey sk1 = new SymmetricKey(); SymmetricKey sk2 = new SymmetricKey(); AbstractKey privateKey = TestKeys.privateKey(0); AbstractKey publicKey1 =TestKeys.privateKey(1).getPublicKey(); AbstractKey publicKey2 = privateKey.getPublicKey(); kr.addKeys( sk1, sk2, privateKey, publicKey1, publicKey2, pk1, pk2 ); kr.addKeys(pk1, pk2); Binder b = kr.toBinder(); KeyRing kr2 = KeyRing.fromBinder(b); assertTrue(kr.keySet().contains(pk1)); assertTrue(kr.keySet().contains(pk2)); assertEquals(pk2, kr.findKey(i2).toArray()[0]); assertEquals(pk2, kr2.findKey(i2).toArray()[0]); final Collection<AbstractKey> keys = kr.findKey(i1); assertTrue(keys.contains(pk1)); assertTrue(keys.contains(pk1)); assertTrue(keys.contains(sk1)); assertTrue(keys.contains(sk2)); assertEquals(4, kr2.findKey(i1).size()); } |
### Question:
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) { throw new RuntimeException("unexpected IOError", e); } } SymmetricKey(); SymmetricKey(byte[] key); SymmetricKey(byte[] key, KeyInfo keyInfo); static SymmetricKey fromPassword(String password, int rounds); static SymmetricKey fromPassword(String password, int rounds, byte[] salt); void setKey(byte[] key); byte[] getKey(); int getBitStrength(); int getSize(); @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); byte[] encrypt(byte[] plaintext); byte[] decrypt(byte[] ciphertext); OutputStream encryptStream(OutputStream outputStream); InputStream decryptStream(InputStream inputStream); EtaEncryptingStream etaEncryptStream(OutputStream out); EtaDecryptingStream etaDecryptStream(InputStream in); byte[] etaEncrypt(byte[] data); byte[] etaSign(byte[] data); byte[] etaDecrypt(byte[] data); static byte[] xor(byte[] src, int value); @Override byte[] pack(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@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, decryptedText); exception.expect(SymmetricKey.AuthenticationFailed.class); cipherText[19] += 1; k.etaDecrypt(cipherText); } |
### Question:
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[] key, KeyInfo keyInfo); static SymmetricKey fromPassword(String password, int rounds); static SymmetricKey fromPassword(String password, int rounds, byte[] salt); void setKey(byte[] key); byte[] getKey(); int getBitStrength(); int getSize(); @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); byte[] encrypt(byte[] plaintext); byte[] decrypt(byte[] ciphertext); OutputStream encryptStream(OutputStream outputStream); InputStream decryptStream(InputStream inputStream); EtaEncryptingStream etaEncryptStream(OutputStream out); EtaDecryptingStream etaDecryptStream(InputStream in); byte[] etaEncrypt(byte[] data); byte[] etaSign(byte[] data); byte[] etaDecrypt(byte[] data); static byte[] xor(byte[] src, int value); @Override byte[] pack(); @Override boolean equals(Object obj); @Override int hashCode(); }### Answer:
@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 = SymmetricKey.xor(src, 0x11); assertArrayEquals(new byte[]{0x11, (byte) 0x44, (byte) 0xEE}, test); } |
### Question:
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(BigDecimal bigDecimalValue); @Override int intValue(); @Override long longValue(); @Override float floatValue(); @Override double doubleValue(); Decimal divide(BigDecimal divisor); Decimal divide(Decimal divisor); Decimal getIntegral(); Decimal getFraction(); Decimal add(Decimal augend); Decimal subtract(Decimal subtrahend); Decimal multiply(Decimal muliplicand); Decimal remainder(Decimal divisor); Decimal add(BigDecimal augend); Decimal subtract(BigDecimal subtrahend); Decimal multiply(BigDecimal muliplicand); Decimal remainder(BigDecimal divisor); Decimal[] divideAndRemainder(BigDecimal divisor); Decimal[] divideAndRemainder(Decimal divisor); Decimal abs(); Decimal negate(); int signum(); int compareTo(Number val); @Override boolean equals(Object x); @Override int hashCode(); @Override String toString(); String toEngineeringString(); String toPlainString(); BigInteger toBigInteger(); Decimal ulp(); static final int SCALE; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; }### Answer:
@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()); } |
### Question:
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 doubleValue(); Decimal divide(BigDecimal divisor); Decimal divide(Decimal divisor); Decimal getIntegral(); Decimal getFraction(); Decimal add(Decimal augend); Decimal subtract(Decimal subtrahend); Decimal multiply(Decimal muliplicand); Decimal remainder(Decimal divisor); Decimal add(BigDecimal augend); Decimal subtract(BigDecimal subtrahend); Decimal multiply(BigDecimal muliplicand); Decimal remainder(BigDecimal divisor); Decimal[] divideAndRemainder(BigDecimal divisor); Decimal[] divideAndRemainder(Decimal divisor); Decimal abs(); Decimal negate(); int signum(); int compareTo(Number val); @Override boolean equals(Object x); @Override int hashCode(); @Override String toString(); String toEngineeringString(); String toPlainString(); BigInteger toBigInteger(); Decimal ulp(); static final int SCALE; static final Decimal ZERO; static final Decimal ONE; static final Decimal TWO; }### Answer:
@Test public void ulp() throws Exception { Decimal x = new Decimal("1000000000000.0000000000000000001"); assertEquals( 1e-19,x.ulp().doubleValue(), 0); } |
### Question:
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; } @Deprecated SimpleRole(String name, @NonNull KeyRecord keyRecord); SimpleRole(String name, Contract contract, @NonNull KeyRecord keyRecord); private SimpleRole(); @Deprecated SimpleRole(String name); SimpleRole(String name,Contract contract); @Deprecated SimpleRole(String name, @NonNull Collection records); SimpleRole(String name, Contract contract, @NonNull Collection records); void addKeyRecord(KeyRecord keyRecord); @Deprecated KeyRecord getKeyRecord(); @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Deprecated @Override Set<KeyAddress> getKeyAddresses(); Set<KeyRecord> getSimpleKeyRecords(); Set<PublicKey> getSimpleKeys(); Set<AnonymousId> getSimpleAnonymousIds(); Set<KeyAddress> getSimpleKeyAddresses(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); boolean isValid(); @Override void initWithDsl(Binder serializedRole); SimpleRole cloneAs(String name,Contract contract); @Deprecated SimpleRole cloneAs(String name); @Override String toString(); boolean isAllowedForKeys(SimpleRole anotherRole); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); }### Answer:
@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); assertEquals(sr, r2); } |
### Question:
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, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; }### Answer:
@Test public void getPublicKey() throws Exception { AbstractPublicKey randomPublicKey4096 = randomPrivateKey4096.getPublicKey(); assertTrue(randomPublicKey4096 instanceof RSAOAEPPublicKey); AbstractPrivateKey rsaPrivateKey = oaepSpec.getPrivateKey(); AbstractPublicKey rsaPublicKey = rsaPrivateKey.getPublicKey(); ((RSAOAEPPublicKey) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); } |
### Question:
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 keyRecords.keySet().iterator().next().getShortAddress(); } else { return keyAddresses.iterator().next(); } } return null; } @Deprecated SimpleRole(String name, @NonNull KeyRecord keyRecord); SimpleRole(String name, Contract contract, @NonNull KeyRecord keyRecord); private SimpleRole(); @Deprecated SimpleRole(String name); SimpleRole(String name,Contract contract); @Deprecated SimpleRole(String name, @NonNull Collection records); SimpleRole(String name, Contract contract, @NonNull Collection records); void addKeyRecord(KeyRecord keyRecord); @Deprecated KeyRecord getKeyRecord(); @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Deprecated @Override Set<KeyAddress> getKeyAddresses(); Set<KeyRecord> getSimpleKeyRecords(); Set<PublicKey> getSimpleKeys(); Set<AnonymousId> getSimpleAnonymousIds(); Set<KeyAddress> getSimpleKeyAddresses(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); boolean isValid(); @Override void initWithDsl(Binder serializedRole); SimpleRole cloneAs(String name,Contract contract); @Deprecated SimpleRole cloneAs(String name); @Override String toString(); boolean isAllowedForKeys(SimpleRole anotherRole); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); }### Answer:
@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(1).getPublicKey()); sr = new SimpleRole("tr1", null, keyAddresses); assertNull(sr.getSimpleAddress()); keyAddresses.remove(keys.get(0).getPublicKey().getShortAddress()); sr = new SimpleRole("tr1", null, keyAddresses); assertEquals(sr.getSimpleAddress(),keys.get(1).getPublicKey().getShortAddress()); sr.addRequiredReference("dummy", Role.RequiredMode.ALL_OF); assertNull(sr.getSimpleAddress()); assertEquals(RoleExtractor.extractSimpleAddress(sr),keys.get(1).getPublicKey().getShortAddress()); } |
### Question:
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 Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); }### Answer:
@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()); }
@Test public void detectsCirculars() throws Exception { Contract c = new Contract(); RoleLink r1 = new RoleLink("bar", "foo"); RoleLink r2 = new RoleLink("foo", "bar"); c.registerRole(r1); c.registerRole(r2); assertNull(r2.resolve()); } |
### Question:
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); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); }### Answer:
@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()); } |
### Question:
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(String name, Contract contract, String roleName); @Deprecated RoleLink(String name, String roleName); @Nullable Role getRole(); @Override T resolve(); T resolve(boolean ignoreRefs); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override @Deprecated Set<PublicKey> getKeys(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override @Deprecated boolean equalKeys(Role otherRole); @Override void initWithDsl(Binder serializedRole); @Override String toString(); @Override Binder serialize(BiSerializer s); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override void anonymize(); }### Answer:
@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(rl); assertEquals(rl.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); rl.addRequiredReference("dummy", Role.RequiredMode.ALL_OF); assertNull(rl.getSimpleAddress()); assertEquals(RoleExtractor.extractSimpleAddress(rl),TestKeys.publicKey(0).getLongAddress()); } |
### Question:
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 contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); void addAll(Collection<Role> roles); Set<Role> getRoles(); ListRole addRole(Role role); void setQuorum(int n); int getQuorum(); void setMode(Mode newMode); Mode getMode(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override void initWithDsl(Binder serializedRole); @Override void setContract(Contract contract); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override String toString(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); }### Answer:
@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.")); } } |
### Question:
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(ignoreRefs); } return null; } ListRole(); ListRole(String name,Contract contract); @Deprecated ListRole(String name); ListRole(String name, Contract contract, Mode mode, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, Mode mode, @NonNull Collection<Role> roles); ListRole(String name, Contract contract, int quorumSize, @NonNull Collection<Role> roles); @Deprecated ListRole(String name, int quorumSize, @NonNull Collection<Role> roles); void addAll(Collection<Role> roles); Set<Role> getRoles(); ListRole addRole(Role role); void setQuorum(int n); int getQuorum(); void setMode(Mode newMode); Mode getMode(); @Override boolean isAllowedForKeysQuantized(Set<? extends AbstractKey> keys); @Override boolean isValid(); @Override void initWithDsl(Binder serializedRole); @Override void setContract(Contract contract); @Override @Deprecated Set<KeyRecord> getKeyRecords(); @Override @Deprecated Set<PublicKey> getKeys(); @Override @Deprecated Set<AnonymousId> getAnonymousIds(); @Override @Deprecated Set<KeyAddress> getKeyAddresses(); @Override String toString(); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer s); @Override void anonymize(); }### Answer:
@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.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); lr.setMode(ListRole.Mode.ANY); assertEquals(lr.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); lr.setQuorum(2); assertNull(lr.getSimpleAddress()); lr.setQuorum(1); assertEquals(lr.getSimpleAddress(),TestKeys.publicKey(0).getLongAddress()); lr.setMode(ListRole.Mode.ANY); SimpleRole sr2 = new SimpleRole("sr2", keyAddresses); lr.addRole(sr2); assertNull(lr.getSimpleAddress()); lr.getRoles().remove(sr2); lr.addRequiredReference("dummy", Role.RequiredMode.ALL_OF); assertNull(lr.getSimpleAddress()); assertEquals(RoleExtractor.extractSimpleAddress(lr),TestKeys.publicKey(0).getLongAddress()); } |
### Question:
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("expected transaction pack"); TransactionPack tp = new TransactionPack(); tp.reconstructed = true; tp.packedBinary = packOrContractBytes; tp.contract = Contract.fromSealedBinary(packOrContractBytes, tp); return tp; } TransactionPack(Contract contract); TransactionPack(); Contract getContract(); Contract getSubItem(HashId id); Contract getSubItem(HashIdentifiable hid); Set<PublicKey> getKeysForPack(); void setContract(Contract c); void addSubItem(Contract subItem); void addReferencedItem(Contract referencedItem); void addTag(String tag, HashId itemId); void addKeys(PublicKey... keys); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer serializer); final boolean isReconstructed(); static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions); static TransactionPack unpack(byte[] packOrContractBytes); synchronized byte[] pack(); Map<HashId, Contract> getSubItems(); Map<HashId, Contract> getReferencedItems(); Map<String, Contract> getTags(); void trace(); void setReferenceContextKeys(Set<PublicKey> referenceEffectiveKeys); Contract findContract(Predicate<Contract> function); static final String TAG_PREFIX_RESERVED; }### Answer:
@Test public void deserializeOldContract() throws Exception { TransactionPack tp = TransactionPack.unpack(c.sealAsV2()); checkSimplePack(tp); } |
### Question:
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()) addKeys(key.getPublicKey()); } TransactionPack(Contract contract); TransactionPack(); Contract getContract(); Contract getSubItem(HashId id); Contract getSubItem(HashIdentifiable hid); Set<PublicKey> getKeysForPack(); void setContract(Contract c); void addSubItem(Contract subItem); void addReferencedItem(Contract referencedItem); void addTag(String tag, HashId itemId); void addKeys(PublicKey... keys); @Override void deserialize(Binder data, BiDeserializer deserializer); @Override Binder serialize(BiSerializer serializer); final boolean isReconstructed(); static TransactionPack unpack(byte[] packOrContractBytes, boolean allowNonTransactions); static TransactionPack unpack(byte[] packOrContractBytes); synchronized byte[] pack(); Map<HashId, Contract> getSubItems(); Map<HashId, Contract> getReferencedItems(); Map<String, Contract> getTags(); void trace(); void setReferenceContextKeys(Set<PublicKey> referenceEffectiveKeys); Contract findContract(Predicate<Contract> function); static final String TAG_PREFIX_RESERVED; }### Answer:
@Test public void serializeNew() throws Exception { TransactionPack tp = new TransactionPack(); tp.setContract(c); checkSimplePack(tp); } |
### Question:
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; if (salt == null) { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), getMaxSaltLength(getBitStrength(), primaryDigest.getDigestSize())); } else { signer = new PSSSigner( RSAEngineFactory.make(), primaryDigest, state.mgf1HashType.makeDigest(), salt); } signer.init(true, new ParametersWithRandom(state.keyParameters, state.rng)); boolean done = false; while (!done) { int availableBytes = input.available(); if (availableBytes <= 0) { done = true; } else { byte[] buffer = new byte[availableBytes]; int howManyBytesRead = input.read(buffer); if (howManyBytesRead <= 0) { done = true; } else { signer.update(buffer, 0, howManyBytesRead); } } } try { return signer.generateSignature(); } catch (CryptoException e) { throw new IOException(String.format("Cannot sign data: %s", e.toString())); } } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; }### Answer:
@Test public void sign() throws Exception { AbstractPrivateKey rsaPrivateKey = pssSpec.getPrivateKey(); assertArrayEquals(rsaPrivateKey.sign(pssSpec.M, HashType.SHA1, RSASSAPSSTestVectors.salt), pssSpec.S); } |
### Question:
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 deserializer); @Override void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); boolean validateMergeFields(Contract changed, Contract c); }### Answer:
@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"); assertNotNull(state); assertTrue(state.size() > 0); Binder data = (Binder) state.get("data"); assertNotNull(data); assertTrue(data.size() > 0); data.remove(FIELD_NAME); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); }
@Test public void shouldNotSplitWithWrongCreatedBySerialize() 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"); assertNotNull(state); assertTrue(state.size() > 0); state.set("createdBy", "other"); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); state.set("createdBy", "owner"); Contract dc3 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc3, false); state.remove("createdBy"); Contract dc4 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc4, false); }
@Test public void shouldNotSplitWithWrongOriginSerialize() 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"); assertNotNull(state); assertTrue(state.size() > 0); HashId origin = HashId.withDigest(Do.randomNegativeBytes(64)); Binder originB = DefaultBiMapper.serialize(origin); state.set("origin", originB); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); state.remove("origin"); Contract dc3 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc3, false); }
@Test public void shouldNotSplitWithWrongParentSerialize() 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"); assertNotNull(state); assertTrue(state.size() > 0); HashId parent = HashId.withDigest(Do.randomNegativeBytes(64)); Binder parentB = DefaultBiMapper.serialize(parent); state.set("parent", parentB); Contract dc2 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc2, false); state.remove("parent"); Contract dc3 = DefaultBiMapper.deserialize(sd2); sealCheckTrace(dc3, false); } |
### Question:
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.keyParameters.getPublicExponent())); put("p", BigIntegers.asUnsignedByteArray(state.keyParameters.getP())); put("q", BigIntegers.asUnsignedByteArray(state.keyParameters.getQ())); if (!state.mgf1HashType.equals(DEFAULT_MGF1_HASH)) { put("mgf1Hash", state.mgf1HashType.getAlgorithmName()); } }}); } } RSAOAEPPrivateKey(); RSAOAEPPrivateKey(byte[] e, byte[] p, byte[] q, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override void generate(int bitStrength, HashType mgf1HashType); void generate(int bitStrength, byte[] e, int certainty, HashType oaepHashType, HashType mgf1HashType); @Override boolean isInitialized(); @Override int getBitStrength(); @Override AbstractPublicKey getPublicKey(); @Override boolean canDecrypt(); @Override byte[] decrypt(byte[] ciphertext); @Override byte[] sign(InputStream input, HashType hashType, @Nullable byte[] salt); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); @Override byte[] pack(); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; }### Answer:
@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); assertFalse(mapRSA.containsKey("mgf1Hash")); AbstractPublicKey randomPublicKey4096 = randomPrivateKey4096.getPublicKey(); Map mapPrivate4096 = randomPrivateKey4096.toHash(), mapPublic4096 = randomPublicKey4096.toHash(); RSAPrivateCrtKeyParameters privateKeyParameters4096 = ((RSAOAEPPrivateKey) randomPrivateKey4096).state.keyParameters; RSAKeyParameters publicKeyParameters4096 = ((RSAOAEPPublicKey) (randomPrivateKey4096.getPublicKey())).state.keyParameters; assertArrayEquals( (byte[]) mapPrivate4096.get("e"), BigIntegers.asUnsignedByteArray(privateKeyParameters4096.getPublicExponent())); assertArrayEquals( (byte[]) mapPrivate4096.get("p"), BigIntegers.asUnsignedByteArray(privateKeyParameters4096.getP())); assertArrayEquals( (byte[]) mapPrivate4096.get("q"), BigIntegers.asUnsignedByteArray(privateKeyParameters4096.getQ())); assertEquals(mapPrivate4096.get("mgf1Hash"), "SHA-512"); assertArrayEquals( (byte[]) mapPublic4096.get("n"), BigIntegers.asUnsignedByteArray(publicKeyParameters4096.getModulus())); assertArrayEquals( (byte[]) mapPublic4096.get("e"), BigIntegers.asUnsignedByteArray(publicKeyParameters4096.getExponent())); assertEquals(mapPublic4096.get("mgf1Hash"), "SHA-512"); } |
### Question:
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 Permission(String name, Role role, Binder params); @Nullable String getId(); void setId(@NonNull String id); Binder getParams(); static Permission forName(String name, Role role, Binder params); @Deprecated boolean isAllowedForKeys(PublicKey... keys); @Deprecated boolean isAllowedForKeys(Collection<PublicKey> keys); @Deprecated boolean isAllowedFor(Collection<PublicKey> keys); boolean isAllowedForKeysQuantized(PublicKey... keys); boolean isAllowedForKeysQuantized(Collection<PublicKey> keys); boolean isAllowedForQuantized(Collection<PublicKey> keys); @Override Binder serialize(BiSerializer serializer); @Override void deserialize(Binder data, BiDeserializer deserializer); final void checkChanges(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); abstract void checkChangesQuantized(Contract contract, Contract changed, Map<String, Delta> stateChanges, Set<Contract> revokingItems, Collection<PublicKey> keys); @Override String toString(); Role getRole(); String getName(); @Override boolean equals(Object obj); @Override int compareTo(Permission o); }### Answer:
@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", "min_value", 33, "max_value", 34, "min_step", 1, "max_step", 1 ) ); changeNumberPermission.setId("changenumber"); contract.addPermission(changeNumberPermission); contract2.addPermission(changeNumberPermission); contract.seal(); contract2.seal(); contract = Contract.fromPackedTransaction(contract.getPackedTransaction()); contract2 = Contract.fromPackedTransaction(contract2.getPackedTransaction()); assertNotNull(contract.get("definition.permissions.changenumber")); assertEquals((Permission)contract.get("definition.permissions.changenumber"),contract2.get("definition.permissions.changenumber")); } |
### Question:
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[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); }### Answer:
@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); assertAlmostSame(es.getCreatedAt(), ZonedDateTime.now()); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.keyId(pubKey)); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.extractKeyId(signature)); }
@Test public void parallelExecutionSign() throws Exception { ExecutorService single = Executors.newSingleThreadExecutor(); ExecutorService multiple = Executors.newCachedThreadPool(); byte[] data = "Hello world".getBytes(); PrivateKey k = new PrivateKey(2048); for(int i=0; i<200; i++) ExtendedSignature.sign(k, data); double t1 = parallelize(single, 1, ()-> { for(int i=0; i<100; i++) ExtendedSignature.sign(k, data); }); System.out.println(t1); double t2 = parallelize(multiple, 4, ()-> { for(int i=0; i<100; i++) ExtendedSignature.sign(k, data); }); System.out.println(t2); assertThat(Math.abs(t1-t2), is(lessThan(0.15))); } |
### Question:
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.get(2)).toArray(), q = ((Bytes) unpackedFromBoss.get(3)).toArray(); return new RSAOAEPPrivateKey( e, p, q, RSAOAEPPrivateKey.DEFAULT_OAEP_HASH, RSAOAEPPrivateKey.DEFAULT_MGF1_HASH, new SecureRandom()); } catch (Throwable e) { return null; } } @Nullable static PrivateKey fromUnikey(@NonNull byte[] bytes); @NonNull static byte[] toUnikey(@NonNull PrivateKey privateKey); }### Answer:
@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.state.keyParameters.getP())); assertArrayEquals( pk1Q, BigIntegers.asUnsignedByteArray(pk1.state.keyParameters.getQ())); } |
### Question:
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(publicKeyBytes); } catch (EncryptionError e) { publicKey = null; } catch (IllegalArgumentException e) { publicKey = null; } return publicKey; } Bytes getKeyId(); ZonedDateTime getCreatedAt(); PublicKey getPublicKey(); static byte[] sign(PrivateKey key, byte[] data); static byte[] sign(PrivateKey key, byte[] data, boolean savePublicKey); static byte[] createTargetSignature(PublicKey publicKey, byte[] data, boolean savePublicKey); @Deprecated static byte[] of(byte[] targetSignature, byte[] sign, byte[] sign2); static byte[] ofSha512AndSha3_384(byte[] targetSignature, byte[] sign512, byte[] sign3_384); static Bytes keyId(AbstractKey key); static Bytes extractKeyId(byte[] signature); static PublicKey extractPublicKey(byte[] signature); byte[] getSignature(); static ExtendedSignature verify(PublicKey key, byte[] signature, byte[] data); }### Answer:
@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); assertAlmostSame(es.getCreatedAt(), ZonedDateTime.now()); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.keyId(pubKey)); assertEquals(ExtendedSignature.keyId(k), ExtendedSignature.extractKeyId(signature)); assertNotNull(es.getPublicKey()); assertEquals(pubKey, es.getPublicKey()); } |
### Question:
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); }### Answer:
@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)); } |
### Question:
RSAOAEPDigestFactory { public static Digest cloneDigest(Digest digest) { try { return digest.getClass().newInstance(); } catch (InstantiationException | IllegalAccessException exc) { exc.printStackTrace(); return digest; } } @Nullable static Digest getDigestByName(String digestName); static Digest cloneDigest(Digest digest); }### Answer:
@Test public void cloneDigest() throws Exception { Digest d1Orig = new SHA512Digest(); Digest d1Clone = RSAOAEPDigestFactory.cloneDigest(d1Orig); assertTrue(d1Clone instanceof SHA512Digest); assertNotEquals(d1Orig, d1Clone); } |
### Question:
RSAOAEPPublicKey extends AbstractPublicKey { @NonNull @Override public byte[] encrypt(byte[] plaintext) throws EncryptionError, IllegalStateException { if (state == null) { throw new IllegalStateException(); } else { try { return state.encryptor.processBlock(plaintext, 0, plaintext.length); } catch (InvalidCipherTextException e) { throw new EncryptionError(String.format("Cannot encode: %s", e.toString())); } } } RSAOAEPPublicKey(); RSAOAEPPublicKey(byte[] n, byte[] e, HashType oaepHashType, HashType mgf1HashType, SecureRandom rng); @Override String toString(); @Override boolean canEncrypt(); @Override int getBitStrength(); @Override boolean isInitialized(); @NonNull @Override byte[] encrypt(byte[] plaintext); @NonNull @Override boolean checkSignature(InputStream input, byte[] signature, HashType hashType, int saltLength); @NonNull @Override String algorithmTag(); @NonNull @Override Map<String, Object> toHash(); @Override void updateFromHash(Map<String, Object> hash); static final HashType DEFAULT_OAEP_HASH; static final HashType DEFAULT_MGF1_HASH; }### Answer:
@Test public void encrypt() throws Exception { AbstractPublicKey rsaPublicKey = oaepSpec.getPublicKey(); ((RSAOAEPPublicKey) rsaPublicKey).resetEncryptor(); assertArrayEquals(rsaPublicKey.encrypt(oaepSpec.M), oaepSpec.C); } |
### Question:
StandaloneBean { public String returnMessage() { return message; } String returnMessage(); }### Answer:
@Test public void testReturnMessage() throws Exception { logger.info("Testing standalone.ejb.StandaloneBean.returnMessage()"); StandaloneBean instance = (StandaloneBean) ctx.lookup("java:global/classes/StandaloneBean"); String expResult = "Greetings!"; String result = instance.returnMessage(); assertEquals(expResult, result); } |
### Question:
ProductTypeRefinerDocProc extends DocumentProcessor { @Override public Progress process(Processing processing) { for (DocumentOperation op : processing.getDocumentOperations()) { if (op instanceof DocumentPut) { DocumentPut put = (DocumentPut) op; Document document = put.getDocument(); if (document.getDataType().isA(MUSIC_DOCUMENT_TYPE)) { logger.info("Before processing: " + document.toJson()); processPut(document); logger.info("After processing: " + document.toJson()); return Progress.DONE; } } } return Progress.DONE; } @Override Progress process(Processing processing); @Override void deconstruct(); }### Answer:
@Test public void testRefinement() { Document doc = new Document(createMusicType(), "id:mynamespace:music::1"); doc.setFieldValue(PRODUCT_TYPE_FIELD_NAME, new StringFieldValue("Media > Music & Sound Recordings > Music Cassette Tapes")); Processing p = getProcessing(new DocumentPut(doc)); DocprocService service = setupDocprocService(new ProductTypeRefinerDocProc()); service.getExecutor().process(p); assertEquals("Media | Music & Sound Recordings | Music Cassette Tapes", doc.getFieldValue(PRODUCT_TYPE_FIELD_NAME).toString()); } |
### Question:
SubqueriesSearcher extends Searcher { public Result search(Query query, Execution execution) { Result result = execution.search(query); execution.fill(result); for (Hit hit : result.hits().asList()) { if (hit.isMeta()) continue; simplifySubqueriesFor("target", hit); hit.removeField("summaryfeatures"); } return result; } SubqueriesSearcher(); Result search(Query query, Execution execution); }### Answer:
@Test public void hit_is_added() throws Exception { try (Application app = Application.fromApplicationPackage( Paths.get("src/test/application"), Networking.disable)) { Search search = app.getJDisc("jdisc").search(); Result result = search.process(ComponentSpecification.fromString("default"), new Query("?query=ignored")); assertEquals(3, result.hits().size()); Hit hit = result.hits().get(0); assertEquals(null, hit.getField("summaryfeatures")); assertEquals(0x100000003L, hit.getField("subqueries(target)")); } } |
### Question:
ProductTypeTokenizerDocProc extends DocumentProcessor { @Override public Progress process(Processing processing) { for (DocumentOperation op : processing.getDocumentOperations()) { if (op instanceof DocumentPut) { DocumentPut put = (DocumentPut) op; Document document = put.getDocument(); if (document.getDataType().isA(MUSIC_DOCUMENT_TYPE)) { logger.info("Before processing: " + document.toJson()); processPut(document); logger.info("After processing: " + document.toJson()); return Progress.DONE; } } } return Progress.DONE; } @Override Progress process(Processing processing); @Override void deconstruct(); }### Answer:
@Test public void testTokenizer() { Document doc = new Document(createMusicType(), "id:mynamespace:music::1"); doc.setFieldValue(PRODUCT_TYPE_FIELD_NAME, new StringFieldValue("Media > Music & Sound Recordings > Music Cassette Tapes")); Processing p = getProcessing(new DocumentPut(doc)); DocprocService service = setupDocprocService(new ProductTypeTokenizerDocProc()); service.getExecutor().process(p); Array<?> tokens = (Array<?>)doc.getFieldValue(PRODUCT_TYPE_TOKENS_FIELD_NAME); assertEquals(55, tokens.size()); assertEquals("M", tokens.get(0).toString()); assertEquals("Media > Music & Sound Recordings > Music Cassette Tapes", tokens.get(54).toString()); } |
### Question:
MetalSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { QueryTree tree = query.getModel().getQueryTree(); if (isMetalQuery(tree)) { OrItem orItem = new OrItem(); orItem.addItem(tree.getRoot()); orItem.addItem(new WordItem("metal", "album")); tree.setRoot(orItem); query.trace("Metal added", true, 2); } return execution.search(query); } @Inject MetalSearcher(MetalNamesConfig config); MetalSearcher(); @Override Result search(Query query, Execution execution); }### Answer:
@Test void testAddedOrTerm1() { MetalNamesConfig.Builder builder = new MetalNamesConfig.Builder(); builder.metalWords(Arrays.asList("hetfield", "metallica", "pantera")); MetalNamesConfig config = new MetalNamesConfig(builder); Chain<Searcher> myChain = new Chain<>(new MinimalQueryInserter(), new MetalSearcher(config)); Execution.Context context = Execution.Context.createContextStub(); Execution execution = new Execution(myChain, context); Result result = execution.search(metalQuery); System.out.println(result.getContext(false).getTrace()); assertAddedOrTerm(metalQuery.getModel().getQueryTree().getRoot()); }
@Test void testAddedOrTerm2() { try (Application app = Application.fromApplicationPackage( FileSystems.getDefault().getPath("src/main/application"), Networking.disable)) { Search search = app.getJDisc("default").search(); Result result = search.process(ComponentSpecification.fromString("metalchain"), metalQuery); System.out.println(result.getContext(false).getTrace()); assertAddedOrTerm(metalQuery.getModel().getQueryTree().getRoot()); } }
@Test void testWithMockBackendProducingHits() { DocumentSourceSearcher docSource = new DocumentSourceSearcher(); Query testQuery = new Query(); testQuery.setTraceLevel(6); testQuery.getModel().getQueryTree().setRoot(new WordItem("drum","album")); Result mockResult = new Result(testQuery); mockResult.hits().add(new Hit("hit:1", 0.9)); mockResult.hits().add(new Hit("hit:2", 0.8)); docSource.addResult(testQuery, mockResult); Chain<Searcher> myChain = new Chain<>(new MetalSearcher(), docSource); Execution.Context context = Execution.Context.createContextStub(); Execution execution = new Execution(myChain, context); Result result = execution.search(testQuery); System.out.println(result.getContext(false).getTrace()); assertEquals(2, result.hits().size()); } |
### Question:
EquivSearcher extends Searcher { @Override public Result search(Query query, Execution execution) { query.trace("Before equivize:" + query.toDetailString(), false, 6); QueryTree tree = query.getModel().getQueryTree(); Item rootItem = tree.getRoot(); rootItem = equivize(rootItem); tree.setRoot(rootItem); query.trace("After equivize:" + query.toDetailString(), false, 6); return execution.search(query); } @Override Result search(Query query, Execution execution); }### Answer:
@Test void testMetallica() { Chain<Searcher> myChain = new Chain<>(new MinimalQueryInserter(), new EquivSearcher()); Execution.Context context = Execution.Context.createContextStub(); Execution execution = new Execution(myChain, context); for (String yql: queries) { Query query = new Query("/search/?yql=" + encode(yql, StandardCharsets.UTF_8)); query.setTraceLevel(6); Result result = execution.search(query); System.out.println(result.getContext(false).getTrace()); } } |
### Question:
ExampleProcessor extends Processor { @SuppressWarnings("unchecked") @Override public Response process(Request request, Execution execution) { request.properties().set("foo", "bar"); Response response = execution.process(request); response.data().add(new StringData(request, message)); return response; } @Inject ExampleProcessor(ExampleProcessorConfig config); @SuppressWarnings("unchecked") @Override Response process(Request request, Execution execution); }### Answer:
@Test public void requireThatResultContainsHelloWorld() { ExampleProcessorConfig.Builder config = new ExampleProcessorConfig.Builder().message("Hello, processor!"); Processor processor = new ExampleProcessor(new ExampleProcessorConfig(config)); Response response = newExecution(processor).process(new Request()); assertEquals("Hello, processor!", response.data().get(0).toString()); } |
### Question:
Out implements SubTraversal<Element, Vertex> { @SuppressWarnings("PMD.ShortMethodName") public static Out of(org.apache.tinkerpop.gremlin.object.structure.Element element) { return of(org.apache.tinkerpop.gremlin.object.reflect.Label.of(element)); } @SuppressWarnings("PMD.ShortMethodName") static Out of(org.apache.tinkerpop.gremlin.object.structure.Element element); @SuppressWarnings("PMD.ShortMethodName") static Out of(
Class<? extends org.apache.tinkerpop.gremlin.object.structure.Element> elementType); @Override GraphTraversal<Element, Vertex> apply(GraphTraversal<Element, Element> traversal); }### Answer:
@Test public void testOutTraversal() { Out out = Out.of(sanFrancisco); traverse(out); verify(traversal, times(1)).out("City"); assertEquals(sanFrancisco.label(), out.label()); } |
### Question:
Classes { public static boolean isSet(Object object) { return object != null && isSet(object.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer:
@Test public void testIsSet() { assertTrue(isSet(new HashSet<>())); assertFalse(isSet(Person.class)); } |
### Question:
Classes { public static boolean isCollection(Object object) { return object != null && isCollection(object.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer:
@Test public void testIsCollection() { assertTrue(isCollection(new ArrayList<>())); assertFalse(isCollection(new PriorityQueue<>())); assertFalse(isCollection(Person.class)); } |
### Question:
Classes { public static boolean isFunctional(Class<?> type) { return is(type, Function.class); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer:
@Test public void testIsFunctional() { assertTrue(isFunctional(HasKeys.class)); assertFalse(isFunctional(Person.class)); } |
### Question:
Classes { @SuppressWarnings({"PMD.ShortMethodName"}) public static boolean is(Class<?> type, Object that) { return that != null && is(type, that.getClass()); } private Classes(); static boolean isElement(Class<?> type); static boolean isVertex(Object object); static boolean isVertex(Class<?> type); static boolean isEdge(Object object); static boolean isEdge(Class<?> type); static boolean isList(Object object); static boolean isList(Class<?> type); static boolean isSet(Object object); static boolean isSet(Class<?> type); static boolean isCollection(Object object); static boolean isCollection(Class<?> type); static boolean isFunctional(Class<?> type); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Object that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Object object, Class<?> that); @SuppressWarnings({"PMD.ShortMethodName"}) static boolean is(Class<?> type, Class<?> that); @SuppressWarnings("unchecked") static void sortCollection(Class<?> clazz, Collection<?> collection); @SneakyThrows @SuppressWarnings("rawtypes") static Collection newCollection(Class<?> clazz); static String name(Class<?> type); }### Answer:
@Test public void testIsSomething() { assertTrue(is(Develops.class, Edge.class)); assertTrue(is(develops, Edge.class)); assertTrue(is(Develops.class, develops)); assertFalse(is(Develops.class, Vertex.class)); assertFalse(is(develops, Vertex.class)); assertFalse(is(Develops.class, marko)); } |
### Question:
Label { @SuppressWarnings("PMD.ShortMethodName") public static String of(Element element) { return of(element.getClass()); } private Label(); @SuppressWarnings("PMD.ShortMethodName") static String of(Element element); @SuppressWarnings("PMD.ShortMethodName") static String of(Class<? extends Element> elementType); }### Answer:
@Test public void testVertexLabelWithAlias() { assertEquals("person", of(Person.class)); assertEquals("person", of(marko)); }
@Test public void testEdgeLabelWithoutAlias() { assertEquals("develops", of(Develops.class)); assertEquals("develops", of(develops)); }
@Test public void testVertexLabelWithoutAlias() { assertEquals("City", of(City.class)); } |