src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
QrdaValidator { private void validateSingleNode(final Node node) { getValidators(node.getType()) .filter(this::isValidationRequired) .forEach(validatorForNode -> { ValidationResult problems = validatorForNode.validateSingleNode(node); errors.addAll(problems.getErrors()); warnings.addAll(problems.getWarnings()); }); } Q...
@Test public void testValidateSingleNode() { Node testRootNode = new Node(TEST_REQUIRED_TEMPLATE_ID); final String testKey = "testKey"; final String testValue = "testValue"; testRootNode.putValue(testKey, testValue); List<Detail> details = objectUnderTest.validate(testRootNode).getErrors(); assertNodeList(nodesPassedIn...
QrdaValidator { public ValidationResult validate(Node rootNode) { DEV_LOG.info("Validating all nodes in the tree"); validateTree(rootNode); return new ValidationResult(errors, warnings); } QrdaValidator(Context context); ValidationResult validate(Node rootNode); }
@Test public void testValidateMultipleNodes() { Node testChildNode1 = new Node(TEST_REQUIRED_TEMPLATE_ID); final String testKey = "testKey"; final String testValue = "testValue"; testChildNode1.putValue(testKey, testValue); Node testChildNode2 = new Node(TEST_REQUIRED_TEMPLATE_ID); testChildNode2.putValue(testKey, test...
Checker { Checker valueIn(LocalizedProblem code, String name, String... values) { boolean contains = false; if (name == null) { details.add(detail(code)); return this; } lastAppraised = node.getValue(name); if (lastAppraised == null || values == null || values.length == 0) { details.add(detail(code)); return this; } fo...
@Test void testValueIn() throws Exception { String key = "My Key"; String value = "My Value"; Node testNode = makeTestNode(key, value); Checker checker = Checker.check(testNode, details); checker.valueIn(ERROR_MESSAGE, key, "No Value" , "Some Value", "My Value"); assertWithMessage("There should be no errors") .that(det...
ValidationServiceImpl implements ValidationService { AllErrors convertQppValidationErrorsToQrda(String validationResponse, JsonWrapper wrapper) { AllErrors errors = new AllErrors(); if (validationResponse == null) { return errors; } Error error = getError(validationResponse); error.getDetails().forEach(detail -> { deta...
@Test void testJsonDesrializationDuplicateEntry() throws IOException { String errorJson = new String(Files.readAllBytes(pathToSubmissionDuplicateEntryError)); convertedErrors = service.convertQppValidationErrorsToQrda(errorJson, qppWrapper); assertWithMessage("Error json should map to AllErrors") .that(convertedErrors....
ValidationServiceImpl implements ValidationService { Error getError(String response) { return JsonHelper.readJson(new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8)), ErrorMessage.class) .getError(); } ValidationServiceImpl(final Environment environment); @PostConstruct void checkForValidationUrlVariabl...
@Test void testQppToQrdaErrorPathConversion() { Detail detail = submissionError.getError().getDetails().get(0); Detail mappedDetails = convertedErrors.getErrors().get(0).getDetails().get(0); assertWithMessage("Json path should be converted to xpath") .that(detail.getLocation().getPath()) .isNotEqualTo(mappedDetails.get...
ManifestVersionService implements VersionService { @Override public String getImplementationVersion() { return Manifests.read("Implementation-Version"); } @Override String getImplementationVersion(); }
@Test void testReadsVersionFromManifest() { Truth.assertThat(new ManifestVersionService().getImplementationVersion()).isNotEmpty(); }
AuditServiceImpl implements AuditService { @Override public CompletableFuture<Metadata> success(ConversionReport conversionReport) { if (noAudit()) { return null; } API_LOG.info("Writing success audit information"); Metadata metadata = initMetadata(conversionReport, Outcome.SUCCESS); Source qrdaSource = conversionRepor...
@Test public void testAuditHappyPath() { when(environment.getProperty(Constants.NO_AUDIT_ENV_VARIABLE)).thenReturn(null); successfulEncodingPrep(); allGood(); underTest.success(report); assertThat(metadata.getQppLocator()).isSameInstanceAs(AN_ID); assertThat(metadata.getSubmissionLocator()).isSameInstanceAs(AN_ID); ass...
AuditServiceImpl implements AuditService { @Override public CompletableFuture<Void> failConversion(ConversionReport conversionReport) { if (noAudit()) { return null; } API_LOG.info("Writing audit information for a conversion failure scenario"); Metadata metadata = initMetadata(conversionReport, Outcome.CONVERSION_ERROR...
@Test public void testAuditConversionFailureHappy() { when(environment.getProperty(Constants.NO_AUDIT_ENV_VARIABLE)).thenReturn(null); errorPrep(); allGood(); underTest.failConversion(report); assertThat(metadata.getConversionErrorLocator()).isSameInstanceAs(AN_ID); assertThat(metadata.getSubmissionLocator()).isSameIns...
AuditServiceImpl implements AuditService { @Override public CompletableFuture<Void> failValidation(ConversionReport conversionReport) { if (noAudit()) { return null; } API_LOG.info("Writing audit information for a validation failure scenario"); Source qrdaSource = conversionReport.getQrdaSource(); Source qppSource = co...
@Test public void testAuditQppValidationFailureHappy() { when(environment.getProperty(Constants.NO_AUDIT_ENV_VARIABLE)).thenReturn(null); successfulEncodingPrep(); errorPrep(); allGood(); underTest.failValidation(report); assertThat(metadata.getRawValidationErrorLocator()).isSameInstanceAs(AN_ID); assertThat(metadata.g...
CpcValidationInfoMap { public Map<String, Map<String, List<String>>> getApmTinNpiCombinationMap() { return apmTinNpiCombinationMap; } CpcValidationInfoMap(InputStream cpcNpiToApmJson); Map<String, Map<String, List<String>>> getApmTinNpiCombinationMap(); }
@Test void test_loadJsonStream() throws Exception { String json = "[" + " {\r\n" + " \"apm_entity_id\": \"T1AR0503\",\r\n" + " \"tin\": \"000333333\",\r\n" + " \"npi\": \"0333333333\"\r\n" + " },\r\n" + " {\r\n" + " \"apm_entity_id\": \"T1AR0518\",\r\n" + " \"tin\": \"000444444\",\r\n" + " \"npi\": \"0444444444\"\r\n" ...
Metadata { public static Metadata create() { Metadata metadata = new Metadata(); metadata.setMetadataVersion(Metadata.CURRENT_VERSION); return metadata; } Metadata(); static Metadata create(); @DynamoDBHashKey(attributeName = "Uuid") @DynamoDBAutoGeneratedKey String getUuid(); void setUuid(String uuid); @DoNotEncrypt @...
@Test void plumbing() { Consumer<Method> consumer = harness(Metadata.create()); Arrays.stream(Metadata.class.getDeclaredMethods()) .filter(this::junk) .forEach(consumer); }
UnprocessedCpcFileData { @Override public String toString() { return MoreObjects.toStringHelper(this) .add("fileId", fileId) .add("filename", "*could hold PII*") .add("apm", apm) .add("conversionDate", conversionDate) .add("validationSuccess", validationSuccess) .add("purpose", purpose) .toString(); } UnprocessedCpcFil...
@Test @DisplayName("should give a string representation of its state") void testToString() { UnprocessedCpcFileData data = new UnprocessedCpcFileData(Metadata.create()); String strung = data.toString(); assertThat(strung).matches(".*fileId.*filename.*apm.*conversionDate.*validationSuccess.*purpose.*"); }
JwtAuthorizationFilter extends BasicAuthenticationFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { String tokenHeader = request.getHeader(HEADER_STRING); if (tokenHeader == null) { chain.doFilter(reques...
@Test public void testDoFilterInternal() throws IOException, ServletException { JwtPayloadHelper payload = new JwtPayloadHelper() .withName(JwtAuthorizationFilter.DEFAULT_ORG_NAME) .withOrgType(ORG_TYPE); request.addHeader("Authorization", JwtTestHelper.createJwt(payload)); JwtAuthorizationFilter testJwtAuthFilter = ne...
ConcurrencyConfig { @Bean public TaskExecutor taskExecutor() { return new SyncTaskExecutor(); } @Bean TaskExecutor taskExecutor(); }
@Test void testIsSync() { TaskExecutor executor = new ConcurrencyConfig().taskExecutor(); assertThat(executor).isInstanceOf(SyncTaskExecutor.class); }
DynamoDbConfig { @Bean public DynamoDBMapper dynamoDbMapper(AmazonDynamoDB dynamoDbClient) { DynamoDBMapper dynamoDbMapper; final Optional<String> kmsKey = getOptionalProperty(Constants.KMS_KEY_ENV_VARIABLE); final Optional<String> tableName = getOptionalProperty(Constants.DYNAMO_TABLE_NAME_ENV_VARIABLE); final Optiona...
@Test public void dbMapperNoAudit() { when(environment.getProperty(eq(Constants.NO_AUDIT_ENV_VARIABLE))).thenReturn("true"); when(environment.getProperty(eq(Constants.DYNAMO_TABLE_NAME_ENV_VARIABLE))).thenReturn(null); when(environment.getProperty(eq(Constants.KMS_KEY_ENV_VARIABLE))).thenReturn(null); DynamoDBMapper dy...
StringHelper { public static String join(Iterable<String> iterable, String separator, String conjunction) { separator = separator + " "; conjunction = conjunction + " "; StringBuilder creator = new StringBuilder(); int timeThroughLoop = 0; Iterator<String> iterator = iterable.iterator(); while (iteratorHasAnotherItem(i...
@Test void testJoining() { String joined = StringHelper.join(Arrays.asList("Dog", "Cow", "Moof"), ",", "or"); assertThat(joined).isEqualTo("Dog, Cow, or Moof"); } @Test void testJoiningOneElement() { String joined = StringHelper.join(Collections.singletonList("Dog"), ",", "or"); assertThat(joined).isEqualTo("Dog"); } @...
DynamoDbConfigFactory { public static DynamoDBMapper createDynamoDbMapper( final AmazonDynamoDB dynamoDb, final DynamoDBMapperConfig config, final AttributeTransformer transformer) { return new DynamoDBMapper(dynamoDb, config, transformer); } private DynamoDbConfigFactory(); static DynamoDBMapper createDynamoDbMapper(...
@Test void testFactory() { DynamoDBMapper dynamoDBMapper = DynamoDbConfigFactory.createDynamoDbMapper(null, null, null); assertWithMessage("The DynamoDB mapper must not be null.").that(dynamoDBMapper).isNotNull(); }
S3Config { @Bean public TransferManager s3TransferManager(AmazonS3 s3Client) { return TransferManagerBuilder.standard().withS3Client(s3Client).build(); } @Bean AmazonS3 s3client(); @Bean TransferManager s3TransferManager(AmazonS3 s3Client); }
@Test public void testTransferManagerIsNotNull() { assertWithMessage("Transfer manager should not be null.") .that(underTest.s3TransferManager(Mockito.mock(AmazonS3.class))).isNotNull(); }
SpecPiiValidator implements PiiValidator { @Override public void validateApmTinNpiCombination(Node node, NodeValidator validator) { String apm = node.getValue(ClinicalDocumentDecoder.PRACTICE_ID); List<String> npiList = Arrays.asList( node.getValue(ClinicalDocumentDecoder.NATIONAL_PROVIDER_IDENTIFIER).split(",")); List...
@Test void testValidCombination() throws Exception { SpecPiiValidator validator = validator("DogCow_APM", "DogCow_NPI"); Node node = node("DogCow_APM", "DogCow_NPI,DogCow_NPI2", "DogCow,DogCow"); NodeValidator nodeValidator = new NodeValidator() { @Override protected void performValidation(Node node) { } }; validator.v...
HealthCheckController { @GetMapping @ResponseStatus(HttpStatus.OK) public @ResponseBody HealthCheck health() { HealthCheck healthCheck = new HealthCheck(); healthCheck.setEnvironmentVariables(new ArrayList<>(System.getenv().keySet())); healthCheck.setSystemProperties( System.getProperties().keySet().stream().map(String...
@Test void testHealthCheckContainsAllSystemProperties() { List<String> systemProperties = System.getProperties().keySet().stream().map(String::valueOf) .collect(Collectors.toList()); Truth.assertThat(service.health().getSystemProperties()).containsExactlyElementsIn(systemProperties); } @Test void testHealthCheckContain...
CpcFileControllerV1 { @PutMapping(value = "/file/{fileId}/{org}", headers = {"Accept=" + Constants.V1_API_ACCEPT}) public ResponseEntity<String> updateFile(@PathVariable("fileId") String fileId, @PathVariable("org") String org, @RequestBody(required = false) CpcFileStatusUpdateRequest request) { if (blockCpcPlusApi()) ...
@Test void testUpdateFileWithNullBodyMarksAsProcessed() { cpcFileControllerV1.updateFile("mock", Constants.CPC_ORG,null); verify(cpcFileService).processFileById("mock", Constants.CPC_ORG); }
CpcFileControllerV1 { @GetMapping(value = "/unprocessed-files/{org}", headers = {"Accept=" + Constants.V1_API_ACCEPT}) public ResponseEntity<List<UnprocessedCpcFileData>> getUnprocessedCpcPlusFiles(@PathVariable("org") String organization) { API_LOG.info("CPC+ unprocessed files request received"); String orgAttribute =...
@Test void testGetUnprocessedFileList() { when(cpcFileService.getUnprocessedCpcPlusFiles(anyString())).thenReturn(expectedUnprocessedCpcFileDataList); ResponseEntity<List<UnprocessedCpcFileData>> qppResponse = cpcFileControllerV1.getUnprocessedCpcPlusFiles(Constants.CPC_ORG); verify(cpcFileService).getUnprocessedCpcPlu...
CpcFileControllerV1 { @GetMapping(value = "/file/{fileId}", headers = {"Accept=" + Constants.V1_API_ACCEPT}) public ResponseEntity<InputStreamResource> getFileById(@PathVariable("fileId") String fileId) throws IOException { API_LOG.info("CPC+ file retrieval request received for fileId {}", fileId); if (blockCpcPlusApi(...
@Test void testGetFileById() throws IOException { InputStreamResource valid = new InputStreamResource(new ByteArrayInputStream("1234".getBytes())); when(cpcFileService.getFileById(anyString())).thenReturn(valid); ResponseEntity<InputStreamResource> response = cpcFileControllerV1.getFileById("meep"); assertThat(IOUtils....
CpcFileControllerV1 { @GetMapping(value = "/qpp/{fileId}", headers = {"Accept=" + Constants.V1_API_ACCEPT}) public ResponseEntity<InputStreamResource> getQppById(@PathVariable("fileId") String fileId) throws IOException { API_LOG.info("CPC+ QPP retrieval request received for fileId {}", fileId); if (blockCpcPlusApi()) ...
@Test void testGetQppById() throws IOException { InputStreamResource valid = new InputStreamResource(new ByteArrayInputStream("1234".getBytes())); when(cpcFileService.getQppById(anyString())).thenReturn(valid); ResponseEntity<InputStreamResource> response = cpcFileControllerV1.getQppById("meep"); assertThat(IOUtils.toS...
ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(TransformException.class) @ResponseBody ResponseEntity<AllErrors> handleTransformException(TransformException exception) { API_LOG.error("Transform exception occurred", exception); auditService.failConversion(exception.getConversion...
@Test void testTransformExceptionStatusCode() { TransformException exception = new TransformException("test transform exception", new NullPointerException(), report); ResponseEntity<AllErrors> responseEntity = objectUnderTest.handleTransformException(exception); assertWithMessage("The response entity's status code must...
ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(QppValidationException.class) @ResponseBody ResponseEntity<AllErrors> handleQppValidationException(QppValidationException exception) { API_LOG.error("Validation exception occurred", exception); auditService.failValidation(exception....
@Test void testQppValidationExceptionStatusCode() { QppValidationException exception = new QppValidationException("test transform exception", new NullPointerException(), report); ResponseEntity<AllErrors> responseEntity = objectUnderTest.handleQppValidationException(exception); assertWithMessage("The response entity's ...
ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(NoFileInDatabaseException.class) @ResponseBody ResponseEntity<String> handleFileNotFoundException(NoFileInDatabaseException exception) { API_LOG.error("A database error occurred", exception); HttpHeaders httpHeaders = new HttpHeader...
@Test void testFileNotFoundExceptionStatusCode() { NoFileInDatabaseException exception = new NoFileInDatabaseException(CpcFileServiceImpl.FILE_NOT_FOUND); ResponseEntity<String> responseEntity = objectUnderTest.handleFileNotFoundException(exception); assertWithMessage("The response entity's status code must be 422.") ....
ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(InvalidFileTypeException.class) @ResponseBody ResponseEntity<String> handleInvalidFileTypeException(InvalidFileTypeException exception) { API_LOG.error("A file type error occurred", exception); HttpHeaders httpHeaders = new HttpHead...
@Test void testInvalidFileTypeExceptionStatusCode() { InvalidFileTypeException exception = new InvalidFileTypeException(CpcFileServiceImpl.FILE_NOT_FOUND); ResponseEntity<String> responseEntity = objectUnderTest.handleInvalidFileTypeException(exception); assertWithMessage("The response entity's status code must be 422....
ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(AmazonServiceException.class) @ResponseBody ResponseEntity<String> handleAmazonException(AmazonServiceException exception) { API_LOG.error("An AWS error occured", exception); return ResponseEntity.status(exception.getStatusCode()) ....
@Test void testHandleAmazonExceptionStatusCode() { AmazonServiceException exception = new AmazonServiceException("some message"); exception.setStatusCode(404); ResponseEntity<String> response = objectUnderTest.handleAmazonException(exception); Truth.assertThat(response.getStatusCodeValue()).isEqualTo(404); } @Test void...
ExceptionHandlerControllerV1 extends ResponseEntityExceptionHandler { @ExceptionHandler(InvalidPurposeException.class) @ResponseBody ResponseEntity<String> handleInvalidPurposeException(InvalidPurposeException exception) { API_LOG.error("An invalid purpose error occured", exception); return ResponseEntity.badRequest() ...
@Test void testHandleInvalidPurposeExceptionExceptionResponseBody() { InvalidPurposeException exception = new InvalidPurposeException("some message"); ResponseEntity<String> response = objectUnderTest.handleInvalidPurposeException(exception); Truth.assertThat(response.getBody()).contains("some message"); }
IDLTools { public static boolean equals(StringBuilder a, StringBuilder b) { if (a.length() == b.length()) { for (int i = 0; i < a.length(); i++) { if (a.charAt(i) != b.charAt(i)) { return false; } } } else { return false; } return true; } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonE...
@Test public void testStringBuilderEquals() { assertTrue("StringBuilders not equal", IDLTools.equals(new StringBuilder("hi"), new StringBuilder("hi"))); assertTrue("StringBuilders not equal", IDLTools.equals(new StringBuilder("a"), new StringBuilder("a"))); assertFalse("StringBuilders equal", IDLTools.equals(new String...
IDLTools { public static boolean epsilonEqualsShortSequence(IDLSequence.Short a, IDLSequence.Short b, double epsilon) { return epsilonEqualsPrimitiveSequence(a::get, b::get, a, b, epsilon); } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonEquals(double a, double b, double epsilon); stat...
@Test public void testEpsilonEqualsSequenceShort() { Short a; Short b; a = new Short(10, "type_1"); b = new Short(10, "type_1"); a.add((short) 0); a.add((short) 4); a.add((short) -1); b.add((short) 0); b.add((short) 4); b.add((short) -1); assertTrue("Sequences not equal", IDLTools.epsilonEqualsShortSequence(a, b, 0.0))...
IDLTools { public static boolean epsilonEqualsIntegerSequence(IDLSequence.Integer a, IDLSequence.Integer b, double epsilon) { return epsilonEqualsPrimitiveSequence(a::get, b::get, a, b, epsilon); } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonEquals(double a, double b, double epsilon)...
@Test public void testEpsilonEqualsSequenceInteger() { Integer a; Integer b; a = new Integer(10, "type_2"); b = new Integer(10, "type_2"); a.add(0); a.add(4); a.add(-1); b.add(0); b.add(4); b.add(-1); assertTrue("Sequences not equal", IDLTools.epsilonEqualsIntegerSequence(a, b, 0.0)); a = new Integer(5, "type_2"); b = ...
IDLTools { public static boolean epsilonEqualsLongSequence(IDLSequence.Long a, IDLSequence.Long b, double epsilon) { return epsilonEqualsPrimitiveSequence(a::get, b::get, a, b, epsilon); } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonEquals(double a, double b, double epsilon); static ...
@Test public void testEpsilonEqualsSequenceLong() { Long a; Long b; a = new Long(10, "type_11"); b = new Long(10, "type_11"); a.add((long) 0); a.add((long) 4); a.add((long) -1); b.add((long) 0); b.add((long) 4); b.add((long) -1); assertTrue("Sequences not equal", IDLTools.epsilonEqualsLongSequence(a, b, 0.0)); a = new ...
IDLTools { public static boolean epsilonEqualsFloatSequence(IDLSequence.Float a, IDLSequence.Float b, double epsilon) { return epsilonEqualsPrimitiveSequence(a::get, b::get, a, b, epsilon); } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonEquals(double a, double b, double epsilon); stat...
@Test public void testEpsilonEqualsSequenceFloat() { Float a; Float b; a = new Float(10, "type_5"); b = new Float(10, "type_5"); a.add((float) 0); a.add((float) 4); a.add((float) -1); b.add((float) 0); b.add((float) 4); b.add((float) -1); assertTrue("Sequences not equal", IDLTools.epsilonEqualsFloatSequence(a, b, 0.0))...
IDLTools { public static boolean epsilonEqualsDoubleSequence(IDLSequence.Double a, IDLSequence.Double b, double epsilon) { return epsilonEqualsPrimitiveSequence(a::get, b::get, a, b, epsilon); } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonEquals(double a, double b, double epsilon); s...
@Test public void testEpsilonEqualsSequenceDouble() { Double a; Double b; a = new Double(10, "type_6"); b = new Double(10, "type_6"); a.add(0.0); a.add(1.5); a.add(-3.0); b.add(0.0); b.add(1.5); b.add(-3.0); assertTrue("Sequences not equal", IDLTools.epsilonEqualsDoubleSequence(a, b, 0.0)); a = new Double(5, "type_6");...
XMLSerializer extends AbstractSerializer<T> { @Override protected T deserialize(JsonNode root) throws IOException { String name = root.get("name").asText(); JsonNode element = root.get("TopicData"); if (topicDataType.getName().equals(name) && element != null && element.isObject()) { JacksonInterchangeSerializer seriali...
@Test public void test() throws IOException { ChatMessagePubSubType dataType = new ChatMessagePubSubType(); XMLSerializer<ChatMessage> serializer = new XMLSerializer<>(dataType); ChatMessage msg = new ChatMessage(); msg.getSender().append("Java"); msg.getMsg().append("Hello World"); String xml = serializer.serializeToS...
IDLTools { public static boolean epsilonEqualsStringBuilder(StringBuilder a, StringBuilder b, double epsilon) { return equals(a, b); } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonEquals(double a, double b, double epsilon); static boolean epsilonEqualsBoolean(boolean a, boolean b, dou...
@Test public void testStringBuilderEpsilonEquals() { assertTrue("StringBuilders not equal", IDLTools.epsilonEqualsStringBuilder(new StringBuilder("hi"), new StringBuilder("hi"), 0.0)); assertFalse("StringBuilders equal", IDLTools.epsilonEqualsStringBuilder(new StringBuilder("hi"), new StringBuilder("bye"), 0.0)); }
IDLTools { public static boolean epsilonEqualsBoolean(boolean a, boolean b, double epsilon) { return a == b; } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonEquals(double a, double b, double epsilon); static boolean epsilonEqualsBoolean(boolean a, boolean b, double epsilon); static boo...
@Test public void testEpsilonEqualsBoolean() { assertTrue("Booleans not equal", IDLTools.epsilonEqualsBoolean(true, true, 0.0)); assertTrue("Booleans not equal", IDLTools.epsilonEqualsBoolean(false, false, 0.0)); assertFalse("Booleans equal", IDLTools.epsilonEqualsBoolean(true, false, 0.0)); }
IDLTools { public static boolean epsilonEquals(double a, double b, double epsilon) { return EuclidCoreTools.epsilonEquals(a, b, epsilon); } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonEquals(double a, double b, double epsilon); static boolean epsilonEqualsBoolean(boolean a, boolean b...
@Test public void testEpsilonEquals() { assertTrue("Doubles not equal", IDLTools.epsilonEquals(0.0, 0.0, 0.0)); assertTrue("Doubles not equal", IDLTools.epsilonEquals(0.1, 0.2, 0.1)); assertFalse("Doubles equal", IDLTools.epsilonEquals(0.0, 0.1, 0.05)); assertFalse("Doubles equal", IDLTools.epsilonEquals(0.0, 5.0, 1.0)...
IDLTools { public static boolean epsilonEqualsEnum(Enum a, Enum b, double epsilon) { if (a == null && b == null) { return true; } else if (a == null || b == null) { return false; } else { return EuclidCoreTools.epsilonEquals(a.ordinal(), b.ordinal(), epsilon); } } static boolean equals(StringBuilder a, StringBuilder b...
@Test public void testEpsilonEqualsEnum() { assertTrue("Enums not equal", IDLTools.epsilonEqualsEnum(SampleEnum.ONE, SampleEnum.ONE, 0.0)); assertTrue("Enums not equal", IDLTools.epsilonEqualsEnum(SampleEnum.TWO, SampleEnum.TWO, 0.0)); assertFalse("Enums equal", IDLTools.epsilonEqualsEnum(SampleEnum.ONE, SampleEnum.TWO...
IDLTools { public static boolean epsilonEqualsStringBuilderSequence(IDLSequence.StringBuilderHolder a, IDLSequence.StringBuilderHolder b, double epsilon) { if (a.size() != b.size()) return false; else for (int i = 0; i < a.size(); i++) { if (!epsilonEqualsStringBuilder(a.get(i), b.get(i), epsilon)) { return false; } } ...
@Test public void testStringBuilderEpsilonEqualsSequence() { StringBuilderHolder a; StringBuilderHolder b; a = new StringBuilderHolder(10, "type_d"); b = new StringBuilderHolder(10, "type_d"); assertTrue("Sequences not equal", IDLTools.epsilonEqualsStringBuilderSequence(a, b, 0.0)); a = new StringBuilderHolder(5, "type...
IDLTools { public static boolean epsilonEqualsEnumSequence(IDLSequence.Enum a, IDLSequence.Enum b, double epsilon) { if (a.size() != b.size()) return false; else for (int i = 0; i < a.size(); i++) { if (!epsilonEqualsEnum(a.get(i), b.get(i), epsilon)) { return false; } } return true; } static boolean equals(StringBuil...
@Test public void testEpsilonEqualsEnumSequence() { Enum<SampleEnum> a; Enum<SampleEnum> b; a = new Enum<>(10, SampleEnum.class, SampleEnum.values()); b = new Enum<>(10, SampleEnum.class, SampleEnum.values()); assertTrue("Sequences not equal", IDLTools.epsilonEqualsEnumSequence(a, b, 0.0)); a = new Enum<>(5, SampleEnum...
IDLTools { public static boolean epsilonEqualsBooleanSequence(IDLSequence.Boolean a, IDLSequence.Boolean b, double epsilon) { if (a.size() != b.size()) return false; else for (int i = 0; i < a.size(); i++) { if (!epsilonEqualsBoolean(a.getBoolean(i), b.getBoolean(i), epsilon)) { return false; } } return true; } static...
@Test public void testEpsilonEqualsSequenceBoolean() { Boolean a; Boolean b; a = new Boolean(10, "type_7"); b = new Boolean(10, "type_7"); assertTrue("Sequences not equal", IDLTools.epsilonEqualsBooleanSequence(a, b, 0.0)); a = new Boolean(5, "type_7"); b = new Boolean(10, "type_7"); assertTrue("Sequences not equal", I...
IDLTools { public static boolean epsilonEqualsByteSequence(IDLSequence.Byte a, IDLSequence.Byte b, double epsilon) { return epsilonEqualsPrimitiveSequence(a::get, b::get, a, b, epsilon); } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonEquals(double a, double b, double epsilon); static ...
@Test public void testEpsilonEqualsSequenceByte() { Byte a; Byte b; a = new Byte(10, "type_9"); b = new Byte(10, "type_9"); assertTrue("Sequences not equal", IDLTools.epsilonEqualsByteSequence(a, b, 0.0)); a = new Byte(5, "type_9"); b = new Byte(10, "type_9"); assertTrue("Sequences not equal", IDLTools.epsilonEqualsByt...
IDLTools { public static boolean epsilonEqualsCharSequence(IDLSequence.Char a, IDLSequence.Char b, double epsilon) { return epsilonEqualsPrimitiveSequence(a::get, b::get, a, b, epsilon); } static boolean equals(StringBuilder a, StringBuilder b); static boolean epsilonEquals(double a, double b, double epsilon); static ...
@Test public void testEpsilonEqualsSequenceChar() { Char a; Char b; a = new Char(10, "type_8"); b = new Char(10, "type_8"); a.add('a'); a.add('b'); a.add('c'); b.add('a'); b.add('b'); b.add('c'); assertTrue("Sequences not equal", IDLTools.epsilonEqualsCharSequence(a, b, 0.0)); a = new Char(5, "type_8"); b = new Char(10...
CopyFile { void copyFileWithSixChannel(String from, String dest) { InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader bufferedReader = null; OutputStream outputStream = null; OutputStreamWriter outputStreamWriter = null; BufferedWriter bufferedWriter = null; try { inputStream = n...
@Test public void testFirst() throws IOException { file.copyFileWithSixChannel(from, dest); validateResultFile(); }
TimeClient { void sendMsg(String msg) { timeClientHandler.sendMsg(msg); } }
@Test(threadPoolSize = 5, invocationCount = 20) public void testClient() throws Exception { startClient(); timeClient.sendMsg(Command.QUERY_TIME); }
TimeServer { public void start() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(Channe...
@Test public void testServer() throws Exception { timeServer.start(); }
InstantiationAndConstructor implements Serializable, Cloneable { @Override protected InstantiationAndConstructor clone() throws CloneNotSupportedException { return (InstantiationAndConstructor) super.clone(); } InstantiationAndConstructor(); InstantiationAndConstructor(String name); }
@Test public void testInitByClone() throws CloneNotSupportedException { String name = "clone"; InstantiationAndConstructor target = new InstantiationAndConstructor(name); log.info("start clone"); InstantiationAndConstructor clone = target.clone(); assertThat(target, equalTo(clone)); assertThat(clone == target, equalTo(...
ClassScanner { public Set<Class<?>> getPackageAllClasses(String basePackage, boolean recursive) { Set<Class<?>> classes = new LinkedHashSet<>(); String packageName = basePackage; if (basePackage.endsWith(".")) { packageName = basePackage.substring(0, basePackage.length() - 1); } String package2Path = packageName.replac...
@Test public void testGetPackageAllClasses() { List<String> list = new ArrayList<>(); list.add("*Base"); ClassScanner scanner = new ClassScanner(true, true, list); System.out.println(ClassScannerTest.class.getPackage().getName()); Set<Class<?>> clazzSet = scanner .getPackageAllClasses(ClassScannerTest.class.getPackage(...
HeapOOM { void createArray() { List<byte[]> data = new ArrayList<>(); while (true) { data.add(new byte[1024 * 1024]); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } void otherThreadWithOOM(); }
@Test public void testCreateArray() { heapOOM.createArray(); }
HeapOOM { void createMap() { Map<Key, String> map = new HashMap<>(); testMap(map); } void otherThreadWithOOM(); }
@Test public void testCreateMap() { heapOOM.createMap(); }
HeapOOM { void createWeakMap() { testMap(new WeakHashMap<>()); } void otherThreadWithOOM(); }
@Test public void testCreateWeakMap() { heapOOM.createWeakMap(); }
HeapOOM { public void otherThreadWithOOM() throws Exception { Thread allocateMemory = new Thread(() -> { List<byte[]> data = new ArrayList<>(); while (true) { data.add(new byte[1024 * 10]); try { TimeUnit.MILLISECONDS.sleep(4); } catch (InterruptedException e) { log.error(e.getMessage(), e); } } }); Thread timer = new ...
@Test public void testOtherThreadWithOOM() throws Exception { heapOOM.otherThreadWithOOM(); }
Main { void transferAllKey() throws InterruptedException { boolean init = initRedisPool(); if (!init) { return; } JedisPool originPool = origin.getJedisPool(); JedisPool targetPool = target.getJedisPool(); try (final Jedis resource = originPool.getResource()) { if (!RedisPools.isAvailable(resource)) { log.error("conn h...
@Test public void testTransferAllKey() throws InterruptedException { RedisPoolProperty origin = new RedisPoolProperty(); origin.setHost("127.0.0.1"); origin.setPort(6667); origin.setTimeout(100); RedisPoolProperty target = new RedisPoolProperty(); target.setHost("127.0.0.1"); target.setPort(6667); target.setTimeout(100...
CopyFile { void copyFileByChar(String from, String dest) { FileReader fileReader = null; FileWriter fileWriter = null; try { fileReader = new FileReader(from); fileWriter = new FileWriter(dest); char[] p = new char[512]; int n; while ((n = fileReader.read(p)) != -1) { fileWriter.write(p, 0, n); String cacheContent = ne...
@Test public void testCopyByChar() throws IOException { file.copyFileByChar(from, dest); validateResultFile(); }
Veterinarian extends Thread { @Override public void run() { while (!shutdown) { seePatient(); try { sleep(restTime); } catch (InterruptedException e) { shutdown(); log.error(e.getMessage(), e); } } } Veterinarian(BlockingQueue<Appointment<Pet>> pets, int pause); @Override void run(); }
@Test public void testRun() throws Exception { BlockingQueue<Appointment<Pet>> lists = new LinkedBlockingQueue<>(); lists.add(new Appointment<>(new Cat("1"))); lists.add(new Appointment<>(new Cat("2"))); lists.add(new Appointment<>(new Dog("1"))); lists.add(new Appointment<>(new Dog("2"))); Veterinarian veterinarian = ...
NeverStopThread { void neverStop() { while (!stop) { } log.info("exit neverStop"); } }
@Test public void testNeverStop() throws Exception { NeverStopThread demo = new NeverStopThread(); Thread thread = new Thread(demo::neverStop); thread.start(); log.info("prepare to stop"); demo.stop(); thread.join(); }
NeverStopThread { void stopWithVolatile() { this.stopWithVolatile = true; } }
@Test public void testVolatile() throws InterruptedException { NeverStopThread demo = new NeverStopThread(); Thread thread = new Thread(demo::normalStopWithVolatile); thread.start(); log.info("prepare to stop"); demo.stopWithVolatile(); thread.join(); }
NeverStopThread { void stopWithSleep() { this.stopWithSleep = true; } }
@Test public void testSleep() throws InterruptedException { NeverStopThread demo = new NeverStopThread(); Thread thread = new Thread(demo::normalStopWithSleep); thread.start(); log.info("prepare to stop"); demo.stopWithSleep(); thread.join(); }
FactoryProducer { static Optional<AbstractFactory> getFactory(String choice) { if (choice.equalsIgnoreCase("SHAPE")) { return Optional.of(new ShapeFactory()); } else if (choice.equalsIgnoreCase("COLOR")) { return Optional.of(new ColorFactory()); } return Optional.empty(); } }
@Test public void testMain() { Optional<AbstractFactory> shapeFactoryOpt = FactoryProducer.getFactory("SHAPE"); Preconditions.checkArgument(shapeFactoryOpt.isPresent()); Optional<Shape> shapeOpt = shapeFactoryOpt.get().getShape("RECTANGLE"); Preconditions.checkArgument(shapeOpt.isPresent()); shapeOpt.get().draw(); Opti...
Decorator extends Invoice { public void printInvoice() { if (ticket != null) { ticket.printInvoice(); } } Decorator(Invoice t); void printInvoice(); }
@Test public void test() { Invoice invoice = new Invoice(); Invoice ticket = new FootDecorator(new HeadDecorator(invoice)); ticket.printInvoice(); System.out.println("----------------"); ticket = new FootDecorator(new HeadDecorator(null)); ticket.printInvoice(); }
MythArrayStack implements MythBaseStack<T> { @Override public void push(T data) { if (isFull()) { return; } top++; this.elementData[top] = data; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unchecked") T pop(); @Override @SuppressWarnings("unchecked") T pee...
@Test public void testPush() { stack.push(1212); assertThat(stack.size(), equalTo(1)); }
MythArrayStack implements MythBaseStack<T> { @Override @SuppressWarnings("unchecked") public T pop() { if (isEmpty()) { throw new IndexOutOfBoundsException(outOfBoundsMsg(0)); } return (T) elementData[top]; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unche...
@Test(expected = IndexOutOfBoundsException.class) public void testPop() { int result = stack.pop(); assertThat(result, equalTo(null)); } @Test public void testPop2() { testPush(); int result = stack.pop(); assertThat(result, equalTo(1212)); }
MythArrayStack implements MythBaseStack<T> { @Override @SuppressWarnings("unchecked") public T peek() { if (isEmpty()) { throw new IndexOutOfBoundsException(outOfBoundsMsg(0)); } return (T) elementData[top]; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unch...
@Test(expected = IndexOutOfBoundsException.class) public void testPeek() { int result = stack.peek(); Assert.assertEquals(1, result); } @Test public void testPeek2() { testPush(); Integer result = stack.peek(); assertThat(result, equalTo(result)); }
CopyFile { void copyFileByByte(String from, String dest) { FileInputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = new FileInputStream(from); outputStream = new FileOutputStream(dest); byte[] buffer = new byte[1024]; while (inputStream.read(buffer) != -1) { outputStream.write(buffe...
@Test public void testCopyByByte() throws IOException { file.copyFileByByte(from, dest); validateResultFile(); }
MythArrayStack implements MythBaseStack<T> { @Override public boolean isEmpty() { return top == -1; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unchecked") T pop(); @Override @SuppressWarnings("unchecked") T peek(); @Override int size(); @Override boolean ...
@Test public void testIsEmpty() { boolean result = stack.isEmpty(); Assert.assertTrue(result); testPush(); assertThat(stack.isEmpty(), equalTo(false)); }
MythArrayStack implements MythBaseStack<T> { public boolean isFull() { return top == maxSize - 1; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unchecked") T pop(); @Override @SuppressWarnings("unchecked") T peek(); @Override int size(); @Override boolean is...
@Test public void testIsFull() { boolean result = stack.isFull(); assertThat(result, equalTo(false)); for (int i = 0; i < 10; i++) { stack.push(i); } result = stack.isFull(); assertThat(result, equalTo(true)); }
MythArrayStack implements MythBaseStack<T> { @Override public void clear() { top = -1; elementData = new Object[DEFAULT_CAPACITY]; } MythArrayStack(); MythArrayStack(int maxSize); @Override void push(T data); @Override @SuppressWarnings("unchecked") T pop(); @Override @SuppressWarnings("unchecked") T peek(); @Override...
@Test public void testClear() { testIsFull(); assertThat(stack.isFull(), equalTo(true)); stack.clear(); assertThat(stack.isEmpty(), equalTo(true)); }
MythLinkedStack implements MythBaseStack<T> { @Override public void push(T data) { Node newNode = new Node(data); if (!Objects.isNull(top)) { newNode.next = top; } top = newNode; } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clea...
@Test public void testPush() { stack.push(1212); assertThat(stack.size(), equalTo(1)); }
MythLinkedStack implements MythBaseStack<T> { @Override public T pop() { if (isEmpty()) { return null; } T temp = top.getData(); top = top.next; return temp; } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clear(); }
@Test public void testPop() throws Exception { testPush(); Integer pop = stack.pop(); assertThat(pop, equalTo(1212)); }
MythLinkedStack implements MythBaseStack<T> { @Override public T peek() { if (Objects.isNull(top)) { return null; } return top.getData(); } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clear(); }
@Test public void testPeek() throws Exception { testPush(); assertThat(stack.peek(), equalTo(1212)); }
MythLinkedStack implements MythBaseStack<T> { @Override public int size() { Node temp = top; if (Objects.isNull(temp)) { return 0; } int count = 0; while (!Objects.isNull(temp)) { count++; temp = top.next; } return count; } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Over...
@Test public void testLength() throws Exception { int result = stack.size(); Assert.assertEquals(0, result); testPush(); assertThat(stack.size(), equalTo(1)); }
MythLinkedStack implements MythBaseStack<T> { @Override public boolean isEmpty() { return Objects.isNull(top); } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clear(); }
@Test public void testIsEmpty() { boolean result = stack.isEmpty(); Assert.assertTrue(result); testPush(); assertThat(stack.isEmpty(), equalTo(false)); }
MythLinkedStack implements MythBaseStack<T> { @Override public void clear() { top = null; } @Override void push(T data); @Override T pop(); @Override T peek(); @Override int size(); @Override boolean isEmpty(); @Override void clear(); }
@Test public void testClear() { testIsEmpty(); stack.clear(); assertThat(stack.size(), equalTo(0)); }
CopyFile { void copyFileByCharBuffer(String from, String dest) { BufferedReader reader = null; BufferedWriter writer = null; try { reader = new BufferedReader(new FileReader(from)); writer = new BufferedWriter(new FileWriter(dest)); String s; while ((s = reader.readLine()) != null) { log.info("line: {}", s); writer.wri...
@Test public void testCopyByCharBuffer() throws IOException { file.copyFileByCharBuffer(from, dest); validateResultFile(); }
AddTwoBigInteger { MythBaseStack<Integer> add(String one, String other) { boolean oneResult = initBigInteger(one, oneStack); boolean otherResult = initBigInteger(other, otherStack); if (!oneResult || !otherResult) { return null; } int flag = 0; while (!oneStack.isEmpty() && !otherStack.isEmpty()) { int sum; sum = oneSt...
@Test public void testAdd() { AddTwoBigInteger addTwoBigInteger = new AddTwoBigInteger(); MythBaseStack<Integer> result = addTwoBigInteger.add("112233", "332211"); String actual = stackToString(result); log.info(": actual={}", actual); assertThat(actual, equalTo("444444")); addTwoBigInteger.clear(); result = addTwoBigI...
MatchBracket { public void match(String origin) { log.info("input string={}", origin); initBrackets(); MythBaseStack<Integer> stack = new MythLinkedStack<>(); for (int i = 0; i < origin.length(); i++) { char charAt = origin.charAt(i); if (leftBrackets.contains(charAt)) { stack.push((int) charAt); continue; } if (rightB...
@Test public void testMatch() { new MatchBracket().match("[[[}]]]"); }
TimeWheel { public boolean add(String id, Callable<?> func, Duration delay) { if (Objects.isNull(delay)) { log.warn("delay is null: id={}", id); return false; } if (Objects.isNull(func)) { log.warn("func is null: id={}", id); return false; } if (cacheTasks.containsKey(id)) { log.warn("task has already exist"); return f...
@Test public void testAdd() throws Exception { boolean result = timeWheel.add("id", () -> null, Duration.ofMillis(10000)); Assert.assertTrue(result); }
MT19937Random { public synchronized int next() { return next(32); } MT19937Random(long seed); final synchronized void setSeed(long seed); final synchronized void setSeed(int[] buf); synchronized int next(); synchronized int next(int bits); }
@Test public void testRandom() { int maxSize = 100000; Set<Integer> pool = new HashSet<>(); for (int i = 0; i < maxSize; i++) { MT19937Random random = new MT19937Random(System.nanoTime()); pool.add(random.next()); } assertThat(pool.size(), equalTo(maxSize)); }
BinarySearch { public int find(int[] arr, int data) { found(arr, 0, arr.length, data); return index + 1; } int find(int[] arr, int data); }
@Test public void testFind() { BinarySearch s = new BinarySearch(); int[] dat = new int[dataScale]; for (int i = 0; i < dat.length; i++) { dat[i] = (int) (Math.random() * dataRange + dataBaseValue); } Insert.INSTANCE.sort(dat); for (int i = 0; i < dat.length; i++) { System.out.print(dat[i] + " "); if ((i + 1) % 10 == 0...
Fibonacci { static int recursiveOne(int num) { if (num < 0) { return 0; } if (num == 1) { return 1; } return recursiveOne(num - 1) + recursiveOne(num - 2); } }
@Test public void testRecursiveOne() throws Exception { general(Fibonacci::recursiveOne, 100); }
Fibonacci { static int loopOne(int num) { if (num <= 0) { return 0; } if (num == 1) { return 1; } int pre = 1; int cur = 1; for (int i = 0; i < num - 2; i++) { int temp = pre; pre = cur; cur = temp + cur; } return cur; } }
@Test public void testLoopOne() { general(Fibonacci::loopOne, 10); }
Fibonacci { static int generalTermFormula(int num) { double temp = Math.sqrt(5); return (int) (1 / temp * (Math.pow((1 + temp) / 2, num) - Math.pow((1 - temp) / 2, num))); } }
@Test public void testGeneralTermFormula() { general(Fibonacci::generalTermFormula, 10); }
SimpleGenericMethod { public static <T> T getMiddle(T[] list) { return list[list.length / 2]; } static T getMiddle(T[] list); static T getMax(T[] list); }
@Test public void testGetMiddle() { Float[] arrays = {2.1f, 4.2f, 3.5f}; Float result = SimpleGenericMethod.getMiddle(arrays); assert result == 4.2f; }
SimpleGenericMethod { public static <T extends Comparable<T> & Serializable> T getMax(T[] list) { T target = list[list.length - 1]; for (int i = list.length - 2; i > -1; i--) { if (target.compareTo(list[i]) < 0) { target = list[i]; } } return target; } static T getMiddle(T[] list); static T getMax(T[] list); }
@Test public void testGetMax() { Score[] scores = { new Score(80f, 50f), new Score(70f, 80f), new Score(100f, 70f) }; Score result = SimpleGenericMethod.getMax(scores); assert result.getNormal() == 100; }
CopyFile { void copyByFiles(Path from, Path dest) throws IOException { Files.copy(from, dest); } }
@Test public void testCopyByFiles() throws IOException { file.copyByFiles(fromPath, destPath); validateResultFile(); }
HumanLoader extends AbstractLoader<String, HumanVO> { @Override Map<String, HumanVO> getMap() { return map; } }
@Test public void testLoad(){ HumanLoader humanLoader = new HumanLoader(); humanLoader.load("xx"); Map<String, HumanVO> data = humanLoader.getMap(); }
ArrayUtils { static <T> T[] create(Class<T> target, int size) { return (T[]) Array.newInstance(target, size); } }
@Test public void testCreateArray() { String[] stringArray = ArrayUtils.create(String.class, 9); System.out.println(Arrays.toString(stringArray)); assert Arrays.stream(stringArray).allMatch(Objects::isNull); }
ArrayUtils { static <T extends Comparable<T>> List<T> sort(List<T> list) { return Arrays.asList(list.toArray((T[]) new Comparable[list.size()])); } }
@Test public void testSort() { List<Integer> list = Arrays.asList(3, 2, 5); List<Integer> result = ArrayUtils.sort(list); log.info("result={}", result); }
ArrayUtils { static <T extends Comparable<T>> T[] sortToArray(List<T> list) { return list.toArray((T[]) new Comparable[list.size()]); } }
@Test public void testSortToArray() { List<Integer> list = Arrays.asList(3, 2, 5); Integer[] result = ArrayUtils.sortToArray(list); log.info("result={}", Arrays.toString(result)); }
SampleUtil { public static <T extends SampleAble> List<T> sampleWithNoRepeated(List<T> list, int count) { return sampleResultWithNoReturn(list, count); } static List<T> sampleWithNoRepeatedAndPutBack(List<T> list, int count); static List<T> sampleWithNoRepeated(List<T> list, int count); static List<T> sampleWith...
@Test public void testSample() { List<DogRef> list = IntStream.rangeClosed(1, 10).mapToObj(i -> new DogRef(i + "", i)) .collect(Collectors.toList()); List<DogRef> result = SampleUtil.sampleWithNoRepeated(list, 2); result.forEach(r -> { System.out.println(r); assertThat(r.getWeight(), lessThan(11)); }); assertThat(resul...
GeneralFileActionDemo { public static boolean createDirectory(String url) throws IOException { FileSystem fileSystem = FileSystem.get(getConfig(url)); boolean result = fileSystem.mkdirs(new Path(url)); log.info("result={}", result); return result; } static boolean createDirectory(String url); static void createNewFile...
@Test public void testCreateDirectory() throws Exception { boolean result = GeneralFileActionDemo.createDirectory(HDFS_HOST + "/flink-batch/test"); assertThat(result, equalTo(true)); }
ConsumerDemo { static void receiveHi() { SimpleMessageExecutor executor = new SimpleMessageExecutor() { @Override public void execute(String message) { log.info("message={}", message); } @Override public String getTopic() { return HI_TOPIC; } }; KafkaConsumerUtil.consumerPlainText(Duration.ofMillis(1000), Collections.s...
@Test public void testReceiveHi() { ConsumerDemo.receiveHi(); }
GeneralFileActionDemo { public static void createNewFile(String url, String content) throws IOException, InterruptedException { FileSystem fs = FileSystem.get(getConfig(url)); FSDataOutputStream os = fs.create(new Path(URI.create(url).getPath())); os.write(content.getBytes(StandardCharsets.UTF_8)); os.flush(); TimeUnit...
@Test public void testCreateFile() throws IOException, InterruptedException { GeneralFileActionDemo.createNewFile(HDFS_HOST + "/input/b.md", "fdasfasdfasd"); }
GeneralFileActionDemo { public static boolean deleteByURL(String url) throws IOException { FileSystem fs = FileSystem.get(getConfig(url)); Path path = new Path(url); boolean isDeleted = fs.deleteOnExit(path); fs.close(); return isDeleted; } static boolean createDirectory(String url); static void createNewFile(String u...
@Test public void testDelete() throws IOException { boolean result = GeneralFileActionDemo .deleteByURL(HDFS_HOST + "/flink-batch/1559008370602_MONTH_2019-03-01_2019-03-27_SPU.csv"); System.out.println(result); }
GeneralFileActionDemo { public static void readHDFSFile(String url) throws Exception { FileSystem fs = FileSystem.get(getConfig(url)); Path path = new Path(url); if (!fs.exists(path)) { throw new Exception("the file is not found ."); } FSDataInputStream is = fs.open(path); BufferedReader bufferedReader = new BufferedRe...
@Test public void testRead() throws Exception { String url = "/flink-batch/1559008370602_MONTH_2019-03-01_2019-03-27_SPU.csv"; GeneralFileActionDemo.readHDFSFile(HDFS_HOST + url); }
Martingale { long martingale(long principal, int count) { if (count < 0) { return principal; } long origin = principal; long start = 1L; for (int i = 0; i < count; i++) { if (principal < start) { log.warn("本金不足: principal={} except={}", principal, start); return principal; } principal -= start; int temp = ThreadLocalRa...
@Test public void testMartingale() { long result = martingale.martingale(99999999L, 2000); log.info("result={}", result); }
CreateKey { public String genericWebStormKey(int minorVersion, int majorVersion, String userName) { BigInteger pubKey = new BigInteger( "BB62FBB57F105CD61B47AE2290FCB3CE1179942DE171BEDDF6BAA1A521B9368B735C7C931902EBA8DE6D160711A6ECC40F4A5E766E9FCDEE8A38715DB572AD3D", 16); BigInteger privKey = new BigInteger( "7BFADCB15...
@Test public void testUse() { CreateKey keyMaker = new CreateKey(); System.out.println(keyMaker.genericWebStormKey(1, 13, "Myth")); }