method2testcases
stringlengths
118
6.63k
### Question: JsonWebTokenAuthenticator implements Authenticator<String, Principal> { public static String createJwtToken(SignatureAlgorithm alg, Key secretKey, Principal principal) { return Jwts.builder().setSubject(principal.getName()).signWith(alg, secretKey).compact(); } JsonWebTokenAuthenticator(Key secretKey, SignatureAlgorithm algorithm); static String createJwtToken(SignatureAlgorithm alg, Key secretKey, Principal principal); @Override Optional<Principal> authenticate(String s); String createJwtToken(Principal principal); }### Answer: @Test(expected = NullPointerException.class) public void testCreateJwtTokenThrowsIfUserIsNull() { final JsonWebTokenAuthenticator authenticator = createValidAuthenticatorInstance(); authenticator.createJwtToken(null); } @Test public void testCreateJwtTokenDoesNotReturnNull() { final Principal Principal = generatePrincipal(); final JsonWebTokenAuthenticator authenticator = createValidAuthenticatorInstance(); final String returnedToken = authenticator.createJwtToken(Principal); assertThat(returnedToken).isNotNull(); } @Test public void testCreateJwtTokenReturnsValidJWTString() { final Key secretKey = createSecretKey(); final Principal Principal = generatePrincipal(); final JsonWebTokenAuthenticator authenticator = createAuthenticatorWithSecretKey(secretKey); final String returnedToken = authenticator.createJwtToken(Principal); assertIsValidJWT(secretKey, returnedToken); }
### Question: CustomAuthenticatorConfig implements AuthenticationConfig { @Override public AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap) { final ClassLoader classLoader = getClassLoader(classPath); final Class<?> klass = loadClass(classLoader, className); final Class<AuthenticationConfig> authConfigClass = toAuthConfigClass(klass); final AuthenticationConfig loadedConfig = loadAuthenticationConfig(properties, authConfigClass); return loadedConfig.createAuthFilter(bootstrap); } CustomAuthenticatorConfig(String className); CustomAuthenticatorConfig(String className, JsonNode properties); @JsonCreator CustomAuthenticatorConfig( @JsonProperty("className") String className, @JsonProperty("classPath") Optional<String> classPath, @JsonProperty("properties") Optional<JsonNode> properties); @Override AuthFilter<?, Principal> createAuthFilter(AuthenticationBootstrap bootstrap); }### Answer: @Test(expected = NullPointerException.class) public void testCreateAuthFilterThrowsIfClassNameIsNull() { final CustomAuthenticatorConfig config = new CustomAuthenticatorConfig(null); config.createAuthFilter(createTypicalAuthBootstrap()); } @Test(expected = RuntimeException.class) public void testCreateAuthFilterIfClassNameDoesNotExistOnClassPath() { final CustomAuthenticatorConfig config = new CustomAuthenticatorConfig(generateClassName()); config.createAuthFilter(createTypicalAuthBootstrap()); } @Test(expected = RuntimeException.class) public void testCreateAuthFilterIfClassDoesNotDeriveFromAuthenticationConfig() { final CustomAuthenticatorConfig config = new CustomAuthenticatorConfig(Object.class.getName()); config.createAuthFilter(createTypicalAuthBootstrap()); } @Test public void testCreateAuthFilterDoesNotThrowIfClassDoesDeriveFromAuthenticationConfig() { final CustomAuthenticatorConfig config = new CustomAuthenticatorConfig(NullCustomAuthConfig.class.getName()); config.createAuthFilter(createTypicalAuthBootstrap()); }
### Question: UserResource { @GET @Path("current") @PermitAll @Operation( summary = "Get the current user", description = "Returns the current user that Jobson believes is calling the API. This entrypoint *always* returns " + "*something*. If authentication is disabled (e.g. guest auth is enabled) then the client's ID is" + " handled as the guest username (usually, 'guest'). All other auth types have an associated username " + "that jobson will extract and return via this entrypoint") public APIUserDetails fetchCurrentUserDetails(@Context SecurityContext context) { return new APIUserDetails(new UserId(context.getUserPrincipal().getName())); } @GET @Path("current") @PermitAll @Operation( summary = "Get the current user", description = "Returns the current user that Jobson believes is calling the API. This entrypoint *always* returns " + "*something*. If authentication is disabled (e.g. guest auth is enabled) then the client's ID is" + " handled as the guest username (usually, 'guest'). All other auth types have an associated username " + "that jobson will extract and return via this entrypoint") APIUserDetails fetchCurrentUserDetails(@Context SecurityContext context); }### Answer: @Test public void testGetCurrentUserReturnsCurrentUserId() { final UserId userId = TestHelpers.generateUserId(); final SecurityContext securityContext = new SecurityContext() { @Override public Principal getUserPrincipal() { return new Principal() { @Override public String getName() { return userId.toString(); } }; } @Override public boolean isUserInRole(String s) { return false; } @Override public boolean isSecure() { return false; } @Override public String getAuthenticationScheme() { return null; } }; final UserResource userResource = new UserResource(); final APIUserDetails APIUserDetails = userResource.fetchCurrentUserDetails(securityContext); assertThat(APIUserDetails.getId()).isEqualTo(userId); }
### Question: JoinFunction implements FreeFunction { @Override public Object call(Object... args) { if (args.length != 2) { throw new RuntimeException(String.format("Invalid number of arguments (%s) supplied to a join function", args.length)); } else if (args[0].getClass() != String.class) { throw new RuntimeException(String.format("%s: Is not a valid first argument to join. It should be a string delimiter", args[0].getClass())); } else if (args[1].getClass() != StringArrayInput.class) { throw new RuntimeException(String.format("%s: Is not a valid second argument to join. It should be a list of strings", args[1].getClass())); } else { final String separator = (String)args[0]; final StringArrayInput entries = (StringArrayInput) args[1]; return String.join(separator, entries.getValues()); } } @Override Object call(Object... args); }### Answer: @Test public void testWhenCalledWithADelimiterAndAnArrayOfStringReturnsAStringJoinedByTheDelimiter() { final JoinFunction joinFunction = new JoinFunction(); final String delimiter = ","; final List<String> items = generateTestData(); final Object ret = joinFunction.call(delimiter, new StringArrayInput(items)); assertThat(ret.getClass()).isEqualTo(String.class); assertThat(ret).isEqualTo(String.join(delimiter, items)); } @Test(expected = RuntimeException.class) public void testWhenCalledWithInvalidTypesThrowsException() { final JoinFunction joinFunction = new JoinFunction(); joinFunction.call(new Object(), new Object()); joinFunction.call(",", new Object()); joinFunction.call(new Object(), generateTestData()); } @Test(expected = RuntimeException.class) public void testThrowsWhenCalledWithInvalidNumberOfArguments() { final JoinFunction joinFunction = new JoinFunction(); joinFunction.call(","); joinFunction.call(",", generateTestData(), new Object()); }
### Question: ToStringFunction implements FreeFunction { @Override public Object call(Object... args) { if (args.length != 1) { throw new RuntimeException(String.format("Incorrect number of arguments (%s), expected 1", args.length)); } else { return args[0].toString(); } } @Override Object call(Object... args); }### Answer: @Test(expected = RuntimeException.class) public void testCallingFunctionWithMoreThanOneArgThrowsException() throws Exception { final ToStringFunction f = new ToStringFunction(); f.call(new Object(), new Object()); } @Test public void testCallingFunctionWithOneArgResultsInToStringOfThatArg() { final ToStringFunction f = new ToStringFunction(); final Integer input = TestHelpers.randomIntBetween(50, 100000); final Object output = f.call(input); assertThat(output).isInstanceOf(String.class); assertThat(output).isEqualTo(input.toString()); }
### Question: FileInput implements JobInput { public String getFilename() { return this.filename; } @JsonCreator FileInput(@JsonProperty(value = "filename") String filename, @JsonProperty(value = "data", required = true) String b64data); FileInput(String filename, byte[] b64data); byte[] getData(); String getFilename(); }### Answer: @Test public void testDefaultsNameWhenNameIsMissing() { final FileInput fi = TestHelpers.readJSONFixture( "fixtures/jobinputs/file/valid-but-missing-name.json", FileInput.class); assertThat(fi.getFilename()).isEqualTo("unnamed"); }
### Question: FilesystemJobSpecDAO implements JobSpecDAO { @Override public Optional<JobSpecSummary> getJobSpecSummaryById(JobSpecId jobSpecId) { return getJobSpecById(jobSpecId).map(JobSpec::toSummary); } FilesystemJobSpecDAO(Path jobSpecsDir); @Override Optional<JobSpec> getJobSpecById(JobSpecId jobSpecId); @Override Map<String, HealthCheck> getHealthChecks(); @Override Optional<JobSpecSummary> getJobSpecSummaryById(JobSpecId jobSpecId); @Override List<JobSpecSummary> getJobSpecSummaries(int pageSize, int page); @Override List<JobSpecSummary> getJobSpecSummaries(int pageSize, int page, String query); }### Answer: @Test public void testGetJobSpecDetailsByIdReturnsEmptyOptionalIfJobSpecIdDoesntExistInTheDir() throws IOException { final Path jobSpecsDir = createTmpDir(FilesystemJobSpecDAOTest.class); final FilesystemJobSpecDAO filesystemJobSpecDAO = new FilesystemJobSpecDAO(jobSpecsDir); final JobSpecId jobSpecId = new JobSpecId(generateRandomBase36String(10)); final Optional<JobSpecSummary> jobSpecDetailsResponse = filesystemJobSpecDAO.getJobSpecSummaryById(jobSpecId); assertThat(jobSpecDetailsResponse.isPresent()).isFalse(); }
### Question: FilesystemJobSpecDAO implements JobSpecDAO { @Override public Map<String, HealthCheck> getHealthChecks() { return singletonMap( FILESYSTEM_SPECS_DAO_DISK_SPACE_HEALTHCHECK, new DiskSpaceHealthCheck( jobSpecsDir.toFile(), FILESYSTEM_SPECS_DAO_DISK_SPACE_WARNING_THRESHOLD_IN_BYTES)); } FilesystemJobSpecDAO(Path jobSpecsDir); @Override Optional<JobSpec> getJobSpecById(JobSpecId jobSpecId); @Override Map<String, HealthCheck> getHealthChecks(); @Override Optional<JobSpecSummary> getJobSpecSummaryById(JobSpecId jobSpecId); @Override List<JobSpecSummary> getJobSpecSummaries(int pageSize, int page); @Override List<JobSpecSummary> getJobSpecSummaries(int pageSize, int page, String query); }### Answer: @Test public void testGetHealthChecksReturnsHealthCheckThatTestsDiskSpace() throws IOException { final FilesystemJobSpecDAO dao = new FilesystemJobSpecDAO(createTmpDir(FilesystemJobsDAOTest.class)); assertThat(dao.getHealthChecks()).containsKeys(FILESYSTEM_SPECS_DAO_DISK_SPACE_HEALTHCHECK); assertThat(dao.getHealthChecks().get(FILESYSTEM_SPECS_DAO_DISK_SPACE_HEALTHCHECK)).isNotNull(); }
### Question: FilesystemJobsDAO implements JobDAO { @Override public Optional<JobSpec> getSpecJobWasSubmittedAgainst(JobId jobId) { return resolveJobDir(jobId).map(Path::toFile).flatMap(this::loadJobSpec); } FilesystemJobsDAO(Path jobsDirectory, IdGenerator idGenerator); @Override boolean jobExists(JobId jobId); @Override List<JobDetails> getJobs(int pageSize, int page); @Override List<JobDetails> getJobs(int pageSize, int pageNumber, String query); @Override Disposable appendStdout(JobId jobId, Observable<byte[]> stdout); @Override Disposable appendStderr(JobId jobId, Observable<byte[]> stderr); @Override PersistedJob persist(ValidJobRequest validJobRequest); @Override void addNewJobStatus(JobId jobId, JobStatus newStatus, String statusMessage); @Override void persistOutput(JobId jobId, JobOutput jobOutput); @Override void remove(JobId jobId); @Override Optional<JobDetails> getJobDetailsById(JobId jobId); @Override Optional<JobSpec> getSpecJobWasSubmittedAgainst(JobId jobId); @Override boolean hasStdout(JobId jobId); @Override Optional<BinaryData> getStdout(JobId jobId); @Override boolean hasStderr(JobId jobId); @Override Optional<BinaryData> getStderr(JobId jobId); @Override Set<JobId> getJobsWithStatus(JobStatus status); @Override boolean hasOutput(JobId jobId, JobOutputId outputId); @Override Optional<BinaryData> getOutput(JobId jobId, JobOutputId outputId); @Override List<JobOutputDetails> getJobOutputs(JobId jobId); @Override boolean hasJobInputs(JobId jobId); @Override Optional<Map<JobExpectedInputId, JsonNode>> getJobInputs(JobId jobId); @Override Map<String, HealthCheck> getHealthChecks(); }### Answer: @Test public void testGetSpecJobWasSubmittedAgainstReturnsOptionalEmptyIfJobDoesntExist() throws IOException { final Path jobsDir = createTmpDir(FilesystemJobsDAOTest.class); final FilesystemJobsDAO dao = createStandardFilesystemDAO(jobsDir); assertThat(dao.getSpecJobWasSubmittedAgainst(generateJobId())).isNotPresent(); }
### Question: FilesystemJobsDAO implements JobDAO { @Override public PersistedJob persist(ValidJobRequest validJobRequest) { final JobId jobId = generateUniqueJobId(); final PersistedJob persistedJob = PersistedJob.createFromValidRequest(validJobRequest, jobId); createNewJobDirectory(persistedJob); return persistedJob; } FilesystemJobsDAO(Path jobsDirectory, IdGenerator idGenerator); @Override boolean jobExists(JobId jobId); @Override List<JobDetails> getJobs(int pageSize, int page); @Override List<JobDetails> getJobs(int pageSize, int pageNumber, String query); @Override Disposable appendStdout(JobId jobId, Observable<byte[]> stdout); @Override Disposable appendStderr(JobId jobId, Observable<byte[]> stderr); @Override PersistedJob persist(ValidJobRequest validJobRequest); @Override void addNewJobStatus(JobId jobId, JobStatus newStatus, String statusMessage); @Override void persistOutput(JobId jobId, JobOutput jobOutput); @Override void remove(JobId jobId); @Override Optional<JobDetails> getJobDetailsById(JobId jobId); @Override Optional<JobSpec> getSpecJobWasSubmittedAgainst(JobId jobId); @Override boolean hasStdout(JobId jobId); @Override Optional<BinaryData> getStdout(JobId jobId); @Override boolean hasStderr(JobId jobId); @Override Optional<BinaryData> getStderr(JobId jobId); @Override Set<JobId> getJobsWithStatus(JobStatus status); @Override boolean hasOutput(JobId jobId, JobOutputId outputId); @Override Optional<BinaryData> getOutput(JobId jobId, JobOutputId outputId); @Override List<JobOutputDetails> getJobOutputs(JobId jobId); @Override boolean hasJobInputs(JobId jobId); @Override Optional<Map<JobExpectedInputId, JsonNode>> getJobInputs(JobId jobId); @Override Map<String, HealthCheck> getHealthChecks(); }### Answer: @Test public void testPersistJobOutputOutputFolderDoesNotExistBeforePersisting() throws IOException { final Path jobsDir = createTmpDir(FilesystemJobsDAOTest.class); final FilesystemJobsDAO dao = createStandardFilesystemDAO(jobsDir); final JobId jobId = dao.persist(STANDARD_VALID_REQUEST).getId(); assertThat(jobsDir.resolve(jobId.toString()).resolve(JOB_DIR_OUTPUTS_DIRNAME)).doesNotExist(); }
### Question: FilesystemJobsDAO implements JobDAO { @Override public void persistOutput(JobId jobId, JobOutput jobOutput) { final Optional<Path> maybeJobDir = resolveJobDir(jobId); if (!maybeJobDir.isPresent()) throw new RuntimeException(jobOutput.getId() + ": cannot be persisted to job " + jobId + ": job dir does not exist"); final Path outputsDir = maybeJobDir.get().resolve(JOB_DIR_OUTPUTS_DIRNAME); createIfDoesNotExist(outputsDir); final Path outputPath = outputsDir.resolve(jobOutput.getId().toString()); writeJobOutputToDisk(jobOutput, outputPath); final Optional<Path> maybeJobOutputsFile = resolveJobFile(jobId, JOB_DIR_OUTPUTS_FILENAME); try { final List<JobOutputDetails> existingJobOutputMetadata = maybeJobOutputsFile.isPresent() ? loadJSON(maybeJobOutputsFile.get(), new TypeReference<List<JobOutputDetails>>(){}) : new ArrayList<>(); final JobOutputDetails jobOutputDetails = new JobOutputDetails( jobOutput.getId(), jobOutput.getData().getSizeOf(), Optional.of(jobOutput.getData().getMimeType()), jobOutput.getName(), jobOutput.getDescription(), jobOutput.getMetadata()); existingJobOutputMetadata.add(jobOutputDetails); writeJSON(resolveJobDir(jobId).get().resolve(JOB_DIR_OUTPUTS_FILENAME), existingJobOutputMetadata); } catch (IOException ex) { throw new RuntimeException(ex); } } FilesystemJobsDAO(Path jobsDirectory, IdGenerator idGenerator); @Override boolean jobExists(JobId jobId); @Override List<JobDetails> getJobs(int pageSize, int page); @Override List<JobDetails> getJobs(int pageSize, int pageNumber, String query); @Override Disposable appendStdout(JobId jobId, Observable<byte[]> stdout); @Override Disposable appendStderr(JobId jobId, Observable<byte[]> stderr); @Override PersistedJob persist(ValidJobRequest validJobRequest); @Override void addNewJobStatus(JobId jobId, JobStatus newStatus, String statusMessage); @Override void persistOutput(JobId jobId, JobOutput jobOutput); @Override void remove(JobId jobId); @Override Optional<JobDetails> getJobDetailsById(JobId jobId); @Override Optional<JobSpec> getSpecJobWasSubmittedAgainst(JobId jobId); @Override boolean hasStdout(JobId jobId); @Override Optional<BinaryData> getStdout(JobId jobId); @Override boolean hasStderr(JobId jobId); @Override Optional<BinaryData> getStderr(JobId jobId); @Override Set<JobId> getJobsWithStatus(JobStatus status); @Override boolean hasOutput(JobId jobId, JobOutputId outputId); @Override Optional<BinaryData> getOutput(JobId jobId, JobOutputId outputId); @Override List<JobOutputDetails> getJobOutputs(JobId jobId); @Override boolean hasJobInputs(JobId jobId); @Override Optional<Map<JobExpectedInputId, JsonNode>> getJobInputs(JobId jobId); @Override Map<String, HealthCheck> getHealthChecks(); }### Answer: @Test(expected = RuntimeException.class) public void testPersistJobOutputThrowsIfJobDoesNotExist() throws IOException { final Path jobsDir = createTmpDir(FilesystemJobsDAOTest.class); final FilesystemJobsDAO dao = createStandardFilesystemDAO(jobsDir); dao.persistOutput(generateJobId(), generateRandomJobOutput()); }
### Question: FilesystemJobsDAO implements JobDAO { @Override public Map<String, HealthCheck> getHealthChecks() { return singletonMap( FILESYSTEM_JOBS_DAO_DISK_SPACE_HEALTHCHECK, new DiskSpaceHealthCheck( this.jobsDirectory.toFile(), FILESYSTEM_JOBS_DAO_DISK_SPACE_WARNING_THRESHOLD_IN_BYTES)); } FilesystemJobsDAO(Path jobsDirectory, IdGenerator idGenerator); @Override boolean jobExists(JobId jobId); @Override List<JobDetails> getJobs(int pageSize, int page); @Override List<JobDetails> getJobs(int pageSize, int pageNumber, String query); @Override Disposable appendStdout(JobId jobId, Observable<byte[]> stdout); @Override Disposable appendStderr(JobId jobId, Observable<byte[]> stderr); @Override PersistedJob persist(ValidJobRequest validJobRequest); @Override void addNewJobStatus(JobId jobId, JobStatus newStatus, String statusMessage); @Override void persistOutput(JobId jobId, JobOutput jobOutput); @Override void remove(JobId jobId); @Override Optional<JobDetails> getJobDetailsById(JobId jobId); @Override Optional<JobSpec> getSpecJobWasSubmittedAgainst(JobId jobId); @Override boolean hasStdout(JobId jobId); @Override Optional<BinaryData> getStdout(JobId jobId); @Override boolean hasStderr(JobId jobId); @Override Optional<BinaryData> getStderr(JobId jobId); @Override Set<JobId> getJobsWithStatus(JobStatus status); @Override boolean hasOutput(JobId jobId, JobOutputId outputId); @Override Optional<BinaryData> getOutput(JobId jobId, JobOutputId outputId); @Override List<JobOutputDetails> getJobOutputs(JobId jobId); @Override boolean hasJobInputs(JobId jobId); @Override Optional<Map<JobExpectedInputId, JsonNode>> getJobInputs(JobId jobId); @Override Map<String, HealthCheck> getHealthChecks(); }### Answer: @Test public void testGetHealthChecksReturnsHealthChecksForRemainingDiskSpace() { final FilesystemJobsDAO dao = createStandardFilesystemDAO(); assertThat(dao.getHealthChecks()).containsKey(FILESYSTEM_JOBS_DAO_DISK_SPACE_HEALTHCHECK); assertThat(dao.getHealthChecks().get(FILESYSTEM_JOBS_DAO_DISK_SPACE_HEALTHCHECK)).isNotNull(); }
### Question: FilesystemUserDAO implements UserDAO { @Override public Optional<UserCredentials> getUserCredentialsById(UserId id) { requireNonNull(id); try { return readUserCredentials() .filter(c -> c.getId().equals(id)) .findFirst(); } catch (IOException e) { throw new RuntimeException(e); } } FilesystemUserDAO(File usersFile); @Override Optional<UserCredentials> getUserCredentialsById(UserId id); @Override boolean addNewUser(UserId id, String authName, String authField); @Override boolean updateUserAuth(UserId id, String authName, String authField); }### Answer: @Test(expected = NullPointerException.class) public void testGetUserDetailsByIdThrowsNPEIfArgsNull() throws IOException { final FilesystemUserDAO dao = new FilesystemUserDAO(tmpFile()); dao.getUserCredentialsById(null); } @Test public void testGetUserDetailsByIdReturnsEmptyOptionalForABogusUserId() throws IOException { final FilesystemUserDAO dao = new FilesystemUserDAO(tmpFile()); assertThat(dao.getUserCredentialsById(generateUserId())).isEmpty(); } @Test public void testGetUserDetailsByIdReturnsUserDetailsFromFilesystem() throws IOException { final UserCredentials userCredentials = generateUserDetails(); final File usersFile = tmpFile(); Files.write(usersFile.toPath(), userCredentials.toUserFileLine().getBytes()); final FilesystemUserDAO dao = new FilesystemUserDAO(usersFile); final Optional<UserCredentials> maybeCredentials = dao.getUserCredentialsById(userCredentials.getId()); assertThat(maybeCredentials).isNotEmpty(); assertThat(maybeCredentials.get()).isEqualTo(userCredentials); } @Test public void testGetUserDetailsByIdReturnsUserDetailsEvenWhenFileContainsBlankLines() throws IOException { final UserCredentials userCredentials = generateUserDetails(); final File usersFile = tmpFile(); final String userLine = userCredentials.toUserFileLine(); final String fileContent = "#somecomment\n\n\n" + userLine + "\n#anothercomment\n"; Files.write(usersFile.toPath(), fileContent.getBytes()); final FilesystemUserDAO dao = new FilesystemUserDAO(usersFile); final Optional<UserCredentials> maybeCredentials = dao.getUserCredentialsById(userCredentials.getId()); assertThat(maybeCredentials).isNotEmpty(); assertThat(maybeCredentials.get()).isEqualTo(userCredentials); }
### Question: SpectralUtils { public static void fft2D_inplace(ComplexDoubleMatrix A) { ComplexDoubleMatrix aTemp = A.transpose(); DoubleFFT_2D fft2d = new DoubleFFT_2D(aTemp.rows, aTemp.columns); fft2d.complexForward(aTemp.data); A.data = aTemp.transpose().data; } static void fft1D_inplace(ComplexDoubleMatrix vector, final int fftLength); static void invfft1D_inplace(ComplexDoubleMatrix vector, final int fftLength); static ComplexDoubleMatrix fft1D(ComplexDoubleMatrix vector, final int fftLength); static ComplexDoubleMatrix invfft1D(ComplexDoubleMatrix vector, final int fftLength); static ComplexDoubleMatrix fft(ComplexDoubleMatrix inMatrix, final int dimension); static ComplexDoubleMatrix invfft(ComplexDoubleMatrix inMatrix, final int dimension); static void fft_inplace(ComplexDoubleMatrix inMatrix, int dimension); static void invfft_inplace(ComplexDoubleMatrix inMatrix, int dimension); static void fft2D_inplace(ComplexDoubleMatrix A); static ComplexDoubleMatrix fft2D(ComplexDoubleMatrix inMatrix); static void fft2D_inplace(DoubleMatrix A); static void invfft2D_inplace(ComplexDoubleMatrix A); static ComplexDoubleMatrix invfft2d(ComplexDoubleMatrix inMatrix); static ComplexDoubleMatrix fftshift(ComplexDoubleMatrix inMatrix); static DoubleMatrix fftshift(DoubleMatrix inMatrix); static void fftshift_inplace(ComplexDoubleMatrix inMatrix); static void fftshift_inplace(DoubleMatrix inMatrix); static ComplexDoubleMatrix ifftshift(ComplexDoubleMatrix inMatrix); static DoubleMatrix ifftshift(DoubleMatrix inMatrix); static void ifftshift_inplace(ComplexDoubleMatrix inMatrix); static void ifftshift_inplace(DoubleMatrix inMatrix); }### Answer: @Test public void testFft2D_inplace() throws Exception { ComplexDoubleMatrix fftMatrix_2D_ACTUAL = complexMatrix_EXPECTED.dup(); SpectralUtils.fft2D_inplace(fftMatrix_2D_ACTUAL); Assert.assertEquals(fftMatrix_2D_EXPECTED, fftMatrix_2D_ACTUAL); ComplexDoubleMatrix fftMatrix_2D_ACTUAL_2 = complexMatrix_EXPECTED_2.dup(); SpectralUtils.fft2D_inplace(fftMatrix_2D_ACTUAL_2); Assert.assertEquals(fftMatrix_2D_EXPECTED_2, fftMatrix_2D_ACTUAL_2); }
### Question: MathUtils { public static boolean isOdd(long value) { return !isEven(value); } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testIsOdd() throws Exception { Assert.assertTrue(MathUtils.isOdd(oddVal_EXPECTED)); Assert.assertFalse(MathUtils.isOdd(evenVal_EXPECTED)); }
### Question: MathUtils { public static boolean isEven(long value) { return value % 2 == 0; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testIsEven() throws Exception { Assert.assertTrue(MathUtils.isEven(evenVal_EXPECTED)); Assert.assertFalse(MathUtils.isEven(oddVal_EXPECTED)); }
### Question: MathUtils { public static boolean isPower2(long value) { return value == 1 || value == 2 || value == 4 || value == 8 || value == 16 || value == 32 || value == 64 || value == 128 || value == 256 || value == 512 || value == 1024 || value == 2048 || value == 4096; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testIsPower2() throws Exception { Assert.assertTrue(MathUtils.isPower2((long) powerOfTwo_EXPECTED)); Assert.assertFalse(MathUtils.isPower2((long) notPowerOfTwo_EXPECTED)); }
### Question: MathUtils { public static double rad2deg(double valueInRadians) { return valueInRadians * Constants.RTOD; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testRad2deg() throws Exception { Assert.assertEquals(valInDegrees_EXPECTED, MathUtils.rad2deg(valInRadians_EXPECTED), DELTA); }
### Question: MathUtils { public static double deg2rad(double valueInDegrees) { return valueInDegrees * Constants.DTOR; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testDeg2rad() throws Exception { Assert.assertEquals(valInRadians_EXPECTED, MathUtils.deg2rad(valInDegrees_EXPECTED), DELTA); }
### Question: MathUtils { public static int[][] distributePoints(final int numOfPoints, final Window window) { final float lines = window.lines(); final float pixels = window.pixels(); int[][] result = new int[numOfPoints][2]; float winP = (float) Math.sqrt(numOfPoints / (lines / pixels)); float winL = numOfPoints / winP; if (winL < winP) { winL = winP; } final int winL_int = (int) Math.floor(winL); final float deltaLin = (lines - 1) / (float) (winL_int - 1); final int totalPix = (int) Math.floor(pixels * winL_int); final float deltaPix = (float) (totalPix - 1) / (float) (numOfPoints - 1); float pix = -deltaPix; float lin; int lCounter = 0; for (int i = 0; i < numOfPoints; i++) { pix += deltaPix; while (Math.floor(pix) >= pixels) { pix -= pixels; lCounter++; } lin = lCounter * deltaLin; result[i][0] = (int) (Math.floor(lin) + window.linelo); result[i][1] = (int) (Math.floor(pix) + window.pixlo); } return result; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testDistributePoints() throws Exception { int[][] distribPnts_ACTUAL = MathUtils.distributePoints(numOfPnts, winForDistribution); for (int i = 0; i < distribPnts_ACTUAL.length; i++) { Assert.assertArrayEquals(distributedPoints_EXPECTED[i], distribPnts_ACTUAL[i]); } }
### Question: MathUtils { public static double[] increment(int m, double begin, double pitch) { double[] array = new double[m]; for (int i = 0; i < m; i++) { array[i] = begin + i * pitch; } return array; } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testIncrement1D() throws Exception { double[] increment_1D_ACTUAL = MathUtils.increment(5, 0, 0.25); Assert.assertArrayEquals(increment_1D_EXPECTED, increment_1D_ACTUAL, DELTA); } @Test public void testIncrement2D() throws Exception { double[][] increment_2D_ACTUAL = MathUtils.increment(5, 2, 0, 0.25); for (int i = 0; i < increment_2D_ACTUAL.length; i++) { Assert.assertArrayEquals(increment_2D_EXPECTED[i], increment_2D_ACTUAL[i], DELTA); } }
### Question: MathUtils { @Deprecated public static double sqr(double value) { return Math.pow(value, 2); } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testSqr() throws Exception { Assert.assertEquals(Math.pow(VALUE, 2), MathUtils.sqr(VALUE), DELTA); }
### Question: MathUtils { @Deprecated public static double sqrt(double value) { return Math.sqrt(value); } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testSqrt() throws Exception { Assert.assertEquals(Math.sqrt(VALUE), MathUtils.sqrt(VALUE), DELTA); }
### Question: MathUtils { public static DoubleMatrix lying(DoubleMatrix inMatrix) { return new DoubleMatrix(inMatrix.toArray()).transpose(); } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testLying() throws Exception{ DoubleMatrix inMatrix = DoubleMatrix.ones(2, 2); DoubleMatrix lying_EXPECTED = DoubleMatrix.ones(1, 4); Assert.assertEquals(lying_EXPECTED, MathUtils.lying(inMatrix)); inMatrix = DoubleMatrix.ones(4, 1); Assert.assertEquals(lying_EXPECTED, MathUtils.lying(inMatrix)); }
### Question: MathUtils { public static DoubleMatrix ramp(final int nRows, final int nColumns) { final double maxHeight = 1; return DoubleMatrix.ones(nRows, 1).mmul(lying(new DoubleMatrix(increment(nColumns, 0, maxHeight / (nColumns - 1))))); } static boolean isEven(long value); static boolean isOdd(long value); static boolean isPower2(long value); static double rad2deg(double valueInRadians); static double deg2rad(double valueInDegrees); static int[][] distributePoints(final int numOfPoints, final Window window); static double[][] distributePointsDoubles(final int numOfPoints, final Window window); static double[] increment(int m, double begin, double pitch); static double[][] increment(int m, int n, double begin, double pitch); static DoubleMatrix ramp(final int nRows, final int nColumns); static DoubleMatrix lying(DoubleMatrix inMatrix); static int randomIntInRange(int min, int max); @Deprecated static double sqrt(double value); @Deprecated static double sqr(double value); }### Answer: @Test public void testRamp() throws Exception { DoubleMatrix ramp_2D_ACTUAL = MathUtils.ramp(nRows, nCols); Assert.assertEquals(ramp_2D_EXPECTED, ramp_2D_ACTUAL); }
### Question: PolyUtils { public static double normalize2(double data, final int min, final int max) { data -= (0.5 * (min + max)); data /= (0.25 * (max - min)); return data; } static double normalize2(double data, final int min, final int max); static double normalize2(double data, final double min, final double max); static DoubleMatrix normalize(DoubleMatrix t); static int degreeFromCoefficients(int numOfCoefficients); static int numberOfCoefficients(final int degree); static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree); static double[] polyFit2D(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree); static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree); static double polyVal1D(double x, double[] coeffs); static double[][] polyval(final double[] x, final double[] y, final double coeff[], int degree); static DoubleMatrix polyval(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final double[] coeff); static double polyval(final double x, final double y, final double[] coeff, int degree); }### Answer: @Test public void testNormalize2() throws Exception { double normValue1_EXPECTED = -2; double normValue2_EXPECTED = -1.636363636363; int min_int = 1; int max_int = 100; double min_double = 1.0; double max_double = 100.; Assert.assertEquals(normValue1_EXPECTED, PolyUtils.normalize2(1, min_int, max_int), DELTA_06); Assert.assertEquals(normValue1_EXPECTED, PolyUtils.normalize2(1, min_double, max_double), DELTA_06); Assert.assertEquals(normValue2_EXPECTED, PolyUtils.normalize2(10, min_int, max_int), DELTA_06); Assert.assertEquals(normValue2_EXPECTED, PolyUtils.normalize2(10, min_double, max_double), DELTA_06); }
### Question: PolyUtils { public static DoubleMatrix normalize(DoubleMatrix t) { return t.sub(t.get(t.length / 2)).div(10.0); } static double normalize2(double data, final int min, final int max); static double normalize2(double data, final double min, final double max); static DoubleMatrix normalize(DoubleMatrix t); static int degreeFromCoefficients(int numOfCoefficients); static int numberOfCoefficients(final int degree); static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree); static double[] polyFit2D(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree); static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree); static double polyVal1D(double x, double[] coeffs); static double[][] polyval(final double[] x, final double[] y, final double coeff[], int degree); static DoubleMatrix polyval(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final double[] coeff); static double polyval(final double x, final double y, final double[] coeff, int degree); }### Answer: @Test public void testNormalize() throws Exception { double[] array_EXPECTED = {1, 2}; double[] normArray_EXPECTED = {-0.1, 0}; Assert.assertEquals(new DoubleMatrix(normArray_EXPECTED), PolyUtils.normalize(new DoubleMatrix(array_EXPECTED))); }
### Question: PolyUtils { public static int degreeFromCoefficients(int numOfCoefficients) { return (int) (0.5 * (-1 + (int) (Math.sqrt((double) (1 + 8 * numOfCoefficients))))) - 1; } static double normalize2(double data, final int min, final int max); static double normalize2(double data, final double min, final double max); static DoubleMatrix normalize(DoubleMatrix t); static int degreeFromCoefficients(int numOfCoefficients); static int numberOfCoefficients(final int degree); static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree); static double[] polyFit2D(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree); static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree); static double polyVal1D(double x, double[] coeffs); static double[][] polyval(final double[] x, final double[] y, final double coeff[], int degree); static DoubleMatrix polyval(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final double[] coeff); static double polyval(final double x, final double y, final double[] coeff, int degree); }### Answer: @Test public void testDegreeFromCoefficients() throws Exception { final int degree_EXPECTED = 5; int degree_ACTUAL = PolyUtils.degreeFromCoefficients(21); Assert.assertEquals(degree_EXPECTED, degree_ACTUAL); }
### Question: PolyUtils { public static int numberOfCoefficients(final int degree) { return (int) (0.5 * (Math.pow(degree + 1, 2) + degree + 1)); } static double normalize2(double data, final int min, final int max); static double normalize2(double data, final double min, final double max); static DoubleMatrix normalize(DoubleMatrix t); static int degreeFromCoefficients(int numOfCoefficients); static int numberOfCoefficients(final int degree); static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree); static double[] polyFit2D(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree); static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree); static double polyVal1D(double x, double[] coeffs); static double[][] polyval(final double[] x, final double[] y, final double coeff[], int degree); static DoubleMatrix polyval(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final double[] coeff); static double polyval(final double x, final double y, final double[] coeff, int degree); }### Answer: @Test public void testNumberOfCoefficients() throws Exception { final int coeffs_EXPECTED = 21; int coeffs_ACTUAL = PolyUtils.numberOfCoefficients(5); Assert.assertEquals(coeffs_EXPECTED, coeffs_ACTUAL); }
### Question: PolyUtils { public static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree) throws IllegalArgumentException { return polyFit(normalize(t), y, degree); } static double normalize2(double data, final int min, final int max); static double normalize2(double data, final double min, final double max); static DoubleMatrix normalize(DoubleMatrix t); static int degreeFromCoefficients(int numOfCoefficients); static int numberOfCoefficients(final int degree); static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree); static double[] polyFit2D(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree); static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree); static double polyVal1D(double x, double[] coeffs); static double[][] polyval(final double[] x, final double[] y, final double coeff[], int degree); static DoubleMatrix polyval(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final double[] coeff); static double polyval(final double x, final double y, final double[] coeff, int degree); }### Answer: @Test public void testPolyFitNormalize() throws Exception { final double[] x = MathUtils.increment(11, 0, 0.1); final double[] y = new double[x.length]; for (int i = 0; i < x.length; i++) { y[i] = erf(x[i]); } final double[] coeff_EXPECTED = {0.52048, 8.786103, -43.780634, -143.72893, 1652.73195}; final double[] coeff_ACTUAL = PolyUtils.polyFitNormalized(new DoubleMatrix(x), new DoubleMatrix(y), 4); Assert.assertArrayEquals(coeff_EXPECTED, coeff_ACTUAL, DELTA_01); }
### Question: PolyUtils { public static double polyVal1D(double x, double[] coeffs) { double sum = 0.0; for (int d = coeffs.length - 1; d >= 0; --d) { sum *= x; sum += coeffs[d]; } return sum; } static double normalize2(double data, final int min, final int max); static double normalize2(double data, final double min, final double max); static DoubleMatrix normalize(DoubleMatrix t); static int degreeFromCoefficients(int numOfCoefficients); static int numberOfCoefficients(final int degree); static double[] polyFitNormalized(DoubleMatrix t, DoubleMatrix y, final int degree); static double[] polyFit2D(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix z, final int degree); static double[] polyFit(DoubleMatrix t, DoubleMatrix y, final int degree); static double polyVal1D(double x, double[] coeffs); static double[][] polyval(final double[] x, final double[] y, final double coeff[], int degree); static DoubleMatrix polyval(final DoubleMatrix x, final DoubleMatrix y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final DoubleMatrix coeff, int degree); static double polyval(final double x, final double y, final double[] coeff); static double polyval(final double x, final double y, final double[] coeff, int degree); }### Answer: @Test public void testPolyVal1d() throws Exception { double[] coeff = {1, 2, 3}; double[] input = {5, 7, 9}; double[] solutionArray_EXPECTED = {86, 162, 262}; for (int i = 0; i < solutionArray_EXPECTED.length; i++) { double solution_EXPECTED = solutionArray_EXPECTED[i]; Assert.assertEquals(solution_EXPECTED, PolyUtils.polyVal1D(input[i], coeff), DELTA_02); } }
### Question: SarUtils { public static ComplexDoubleMatrix multilook(final ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorColumn) { if (factorRow == 1 && factorColumn == 1) { return inputMatrix; } logger.debug("multilook input [inputMatrix] size: " + inputMatrix.length + " lines: " + inputMatrix.rows + " pixels: " + inputMatrix.columns); if (inputMatrix.rows / factorRow == 0 || inputMatrix.columns / factorColumn == 0) { logger.debug("Multilooking was not necessary for this inputMatrix: inputMatrix.rows < mlR or buffer.columns < mlC"); return inputMatrix; } ComplexDouble sum; final ComplexDouble factorLP = new ComplexDouble(factorRow * factorColumn); ComplexDoubleMatrix outputMatrix = new ComplexDoubleMatrix(inputMatrix.rows / factorRow, inputMatrix.columns / factorColumn); for (int i = 0; i < outputMatrix.rows; i++) { for (int j = 0; j < outputMatrix.columns; j++) { sum = new ComplexDouble(0); for (int k = i * factorRow; k < (i + 1) * factorRow; k++) { for (int l = j * factorColumn; l < (j + 1) * factorColumn; l++) { sum.addi(inputMatrix.get(k, l)); } } outputMatrix.put(i, j, sum.div(factorLP)); } } return outputMatrix; } static ComplexDoubleMatrix oversample(ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorCol); static DoubleMatrix intensity(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix magnitude(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix angle(final ComplexDoubleMatrix cplxData); @Deprecated static DoubleMatrix coherence(final ComplexDoubleMatrix inputMatrix, final ComplexDoubleMatrix normsMatrix, final int winL, final int winP); static DoubleMatrix coherence2(final ComplexDoubleMatrix input, final ComplexDoubleMatrix norms, final int winL, final int winP); static ComplexDoubleMatrix multilook(final ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorColumn); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static void computeIfg_inplace(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData, final int ovsFactorAz, final int ovsFactorRg); }### Answer: @Test public void testMultilook() throws Exception { int[] mlookFactorAz = new int[]{1, 2, 5, 5}; int[] mlookFactorRg = new int[]{2, 2, 1, 5}; for (int i = 0; i < mlookFactorAz.length; i++) { int facAz = mlookFactorAz[i]; int facRg = mlookFactorRg[i]; ComplexDoubleMatrix cplxData_mlook_ACTUAL = SarUtils.multilook(cplxData, facAz, facRg); String fileName = testDataLocation + "testdata_mlook_" + facAz + "_" + facRg + ".cr8"; ComplexDoubleMatrix cplxData_mlook_EXPECTED = readCplxDoubleData(fileName, cplxData_mlook_ACTUAL.rows, cplxData_mlook_ACTUAL.columns, ByteOrder.LITTLE_ENDIAN); Assert.assertArrayEquals(cplxData_mlook_EXPECTED.toDoubleArray(), cplxData_mlook_ACTUAL.toDoubleArray(), DELTA_08); } }
### Question: SarUtils { public static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData) throws Exception { return LinearAlgebraUtils.dotmult(masterData, slaveData.conj()); } static ComplexDoubleMatrix oversample(ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorCol); static DoubleMatrix intensity(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix magnitude(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix angle(final ComplexDoubleMatrix cplxData); @Deprecated static DoubleMatrix coherence(final ComplexDoubleMatrix inputMatrix, final ComplexDoubleMatrix normsMatrix, final int winL, final int winP); static DoubleMatrix coherence2(final ComplexDoubleMatrix input, final ComplexDoubleMatrix norms, final int winL, final int winP); static ComplexDoubleMatrix multilook(final ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorColumn); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static void computeIfg_inplace(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData, final int ovsFactorAz, final int ovsFactorRg); }### Answer: @Test public void testComplexOvsmpIfg() throws Exception { int[] ovsmpAz = new int[]{1, 2, 2, 3}; int[] ovsmpRg = new int[]{2, 1, 2, 3}; for (int i = 0; i < ovsmpAz.length; i++) { int ovsAz = ovsmpAz[i]; int ovsRg = ovsmpRg[i]; String fileTestDataName = testDataLocation + "testdata_ifg_ovsmp_" + ovsAz + "_" + ovsRg + ".cr8"; ComplexDoubleMatrix ifgCplx_EXPECTED = readCplxDoubleData(fileTestDataName, ovsAz * nRows, ovsRg * nCols, ByteOrder.LITTLE_ENDIAN); ComplexDoubleMatrix ifgCplx_ACTUAL = SarUtils.computeIfg(cplxData, cplxData, ovsAz, ovsRg); Assert.assertEquals(ifgCplx_EXPECTED, ifgCplx_ACTUAL); } } @Test public void testComplexIfg() throws Exception { String fileTestDataName = testDataLocation + "testdata_ifg_ovsmp_" + 1 + "_" + 1 + ".cr8"; ComplexDoubleMatrix ifgCplx_EXPECTED = readCplxDoubleData(fileTestDataName, nRows, nCols, ByteOrder.LITTLE_ENDIAN); ComplexDoubleMatrix ifgCplx_ACTUAL = SarUtils.computeIfg(cplxData, cplxData); Assert.assertEquals(ifgCplx_EXPECTED, ifgCplx_ACTUAL); }
### Question: SarUtils { public static DoubleMatrix intensity(final ComplexDoubleMatrix inputMatrix) { return pow(inputMatrix.real(), 2).add(pow(inputMatrix.imag(), 2)); } static ComplexDoubleMatrix oversample(ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorCol); static DoubleMatrix intensity(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix magnitude(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix angle(final ComplexDoubleMatrix cplxData); @Deprecated static DoubleMatrix coherence(final ComplexDoubleMatrix inputMatrix, final ComplexDoubleMatrix normsMatrix, final int winL, final int winP); static DoubleMatrix coherence2(final ComplexDoubleMatrix input, final ComplexDoubleMatrix norms, final int winL, final int winP); static ComplexDoubleMatrix multilook(final ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorColumn); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static void computeIfg_inplace(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData, final int ovsFactorAz, final int ovsFactorRg); }### Answer: @Test public void testIntensity() throws Exception { DoubleMatrix intensity_ACTUAL = SarUtils.intensity(cplxData); Assert.assertEquals(DoubleMatrix.ones(cplxData.rows, cplxData.columns), intensity_ACTUAL); }
### Question: SarUtils { public static DoubleMatrix magnitude(final ComplexDoubleMatrix inputMatrix) { return sqrt(intensity(inputMatrix)); } static ComplexDoubleMatrix oversample(ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorCol); static DoubleMatrix intensity(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix magnitude(final ComplexDoubleMatrix inputMatrix); static DoubleMatrix angle(final ComplexDoubleMatrix cplxData); @Deprecated static DoubleMatrix coherence(final ComplexDoubleMatrix inputMatrix, final ComplexDoubleMatrix normsMatrix, final int winL, final int winP); static DoubleMatrix coherence2(final ComplexDoubleMatrix input, final ComplexDoubleMatrix norms, final int winL, final int winP); static ComplexDoubleMatrix multilook(final ComplexDoubleMatrix inputMatrix, final int factorRow, final int factorColumn); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static void computeIfg_inplace(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData); static ComplexDoubleMatrix computeIfg(final ComplexDoubleMatrix masterData, final ComplexDoubleMatrix slaveData, final int ovsFactorAz, final int ovsFactorRg); }### Answer: @Test public void testMagnitude() throws Exception { DoubleMatrix magnitude_ACTUAL = SarUtils.magnitude(cplxData); Assert.assertEquals(DoubleMatrix.ones(cplxData.rows, cplxData.columns), magnitude_ACTUAL); }
### Question: Ellipsoid { public void showdata() { logger.info("ELLIPSOID: \tEllipsoid used (orbit, output): " + name + "."); logger.info("ELLIPSOID: a = " + a); logger.info("ELLIPSOID: b = " + b); logger.info("ELLIPSOID: e2 = " + e2); logger.info("ELLIPSOID: e2' = " + e2b); } Ellipsoid(); Ellipsoid(final double semiMajor, final double semiMinor); Ellipsoid(Ellipsoid ell); void showdata(); static double[] xyz2ell(final Point xyz); static Point ell2xyz(final double phi, final double lambda, final double height); static Point ell2xyz(final double[] phiLambdaHeight); static Point ell2xyz(final GeoPoint geoPoint, final double height); static Point ell2xyz(final GeoPoint geoPoint); static void ell2xyz(final GeoPoint geoPoint, double[] xyz); static void ell2xyz(final GeoPoint geoPoint, final double height, final double[] xyz); static double a; static double b; static String name; }### Answer: @Ignore @Test public void testShowdata() throws Exception { inputEll.showdata(); }
### Question: Ellipsoid { public static double[] xyz2ell(final Point xyz) { final double r = Math.sqrt(Math.pow(xyz.x, 2) + Math.pow(xyz.y, 2)); final double nu = Math.atan2((xyz.z * a), (r * b)); final double sin3 = Math.pow(Math.sin(nu), 3); final double cos3 = Math.pow(Math.cos(nu), 3); final double phi = Math.atan2((xyz.z + e2b * b * sin3), (r - e2 * a * cos3)); final double lambda = Math.atan2(xyz.y, xyz.x); final double N = computeEllipsoidNormal(phi); final double height = (r / Math.cos(phi)) - N; return new double[]{phi, lambda, height}; } Ellipsoid(); Ellipsoid(final double semiMajor, final double semiMinor); Ellipsoid(Ellipsoid ell); void showdata(); static double[] xyz2ell(final Point xyz); static Point ell2xyz(final double phi, final double lambda, final double height); static Point ell2xyz(final double[] phiLambdaHeight); static Point ell2xyz(final GeoPoint geoPoint, final double height); static Point ell2xyz(final GeoPoint geoPoint); static void ell2xyz(final GeoPoint geoPoint, double[] xyz); static void ell2xyz(final GeoPoint geoPoint, final double height, final double[] xyz); static double a; static double b; static String name; }### Answer: @Test public void testXyz2ell() throws Exception { double[] phi_lambda_height = Ellipsoid.xyz2ell(new Point(cr_XYZ_expected)); Assert.assertEquals(cr_GEO_expected[0], Math.toDegrees(phi_lambda_height[0]), deltaGEO); Assert.assertEquals(cr_GEO_expected[1], Math.toDegrees(phi_lambda_height[1]), deltaGEO); Assert.assertEquals(cr_GEO_expected[2], phi_lambda_height[2], deltaXYZ); }
### Question: Ellipsoid { public static Point ell2xyz(final double phi, final double lambda, final double height) throws IllegalArgumentException { if (phi > Math.PI || phi < -Math.PI || lambda > Math.PI || lambda < -Math.PI) { throw new IllegalArgumentException("Ellipsoid.ell2xyz : input values for phi/lambda have to be in radians!"); } final double N = computeEllipsoidNormal(phi); final double Nph = N + height; return new Point( Nph * Math.cos(phi) * Math.cos(lambda), Nph * Math.cos(phi) * Math.sin(lambda), (Nph - e2 * N) * Math.sin(phi)); } Ellipsoid(); Ellipsoid(final double semiMajor, final double semiMinor); Ellipsoid(Ellipsoid ell); void showdata(); static double[] xyz2ell(final Point xyz); static Point ell2xyz(final double phi, final double lambda, final double height); static Point ell2xyz(final double[] phiLambdaHeight); static Point ell2xyz(final GeoPoint geoPoint, final double height); static Point ell2xyz(final GeoPoint geoPoint); static void ell2xyz(final GeoPoint geoPoint, double[] xyz); static void ell2xyz(final GeoPoint geoPoint, final double height, final double[] xyz); static double a; static double b; static String name; }### Answer: @Test public void testEll2xyz() throws Exception { Point cr4_XYZ_actual = Ellipsoid.ell2xyz(cr_GEO_expected[0] * DTOR, cr_GEO_expected[1] * DTOR, cr_GEO_expected[2]); for (int i = 0; i < cr_XYZ_expected.length; i++) { Assert.assertEquals(cr_XYZ_expected[i],cr4_XYZ_actual.toArray()[i], deltaXYZ); } } @Test public void testEll2xyz_ARRAYS() throws Exception { GeoPoint geoPoint_EXPECTED = new GeoPoint(cr_GEO_expected[0], cr_GEO_expected[1]); double[] xyz_ACTUAL = new double[3]; Ellipsoid.ell2xyz(geoPoint_EXPECTED, cr_GEO_expected[2], xyz_ACTUAL); for (int i = 0; i < cr_XYZ_expected.length; i++) { Assert.assertEquals(cr_XYZ_expected[i], xyz_ACTUAL[i], deltaXYZ); } }
### Question: DInSAR { public DInSAR(SLCImage masterMeta, Orbit masterOrbit, SLCImage slaveDefoMeta, Orbit slaveDefoOrbit, SLCImage topoSlaveMeta, Orbit slaveTopoOrbit) { this.masterMeta = masterMeta; this.masterOrbit = masterOrbit; this.slaveDefoMeta = slaveDefoMeta; this.slaveDefoOrbit = slaveDefoOrbit; this.topoSlaveMeta = topoSlaveMeta; this.slaveTopoOrbit = slaveTopoOrbit; dataWindow = masterMeta.getCurrentWindow(); } DInSAR(SLCImage masterMeta, Orbit masterOrbit, SLCImage slaveDefoMeta, Orbit slaveDefoOrbit, SLCImage topoSlaveMeta, Orbit slaveTopoOrbit); void setDataWindow(Window dataWindow); void setTileWindow(Window tileWindow); void setTopoData(DoubleMatrix topoData); void setDefoData(ComplexDoubleMatrix defoData); ComplexDoubleMatrix getDefoData(); @Deprecated void dinsar(); void computeBperpRatios(); void applyDInSAR(final Window tileWindow, final ComplexDoubleMatrix defoData, final DoubleMatrix topoData); static double[] linspace(final int lower, final int upper, final int size); static double[] linspace(final int lower, final int upper); }### Answer: @Test public void testDinsar() throws Exception { ComplexDoubleMatrix defoData = cplxIfg.dup(); StopWatch watch = new StopWatch(); watch.start(); DInSAR dinsar = new DInSAR(masterMeta, masterOrbit, defoSlaveMeta, defoSlaveOrbit, topoSlaveMeta, topoSlaveOrbit); dinsar.setDataWindow(totalDataWindow); dinsar.computeBperpRatios(); dinsar.applyDInSAR(tileWindow, defoData, topoPhase); watch.stop(); logger.info("Total processing time: {} milli-seconds", watch.getElapsedTime()); ComplexDoubleMatrix expected = SarUtils.computeIfg(defoCplxIfg, defoData); int numOfElements = expected.length; double[] defoDelta = new double[numOfElements]; for (int i = 0; i < numOfElements; i++) { defoDelta[i] = Math.atan2(expected.getImag(i), expected.getReal(i)) * PHASE2DEFO; } Assert.assertArrayEquals(DoubleMatrix.zeros(defoCplxIfg.length).toArray(), defoDelta, DELTA_02); } @Test public void testDinsar() throws Exception { ComplexDoubleMatrix defoData = cplxIfg.dup(); StopWatch watch = new StopWatch(); watch.start(); DInSAR dinsar = new DInSAR(masterMeta, masterOrbit, defoSlaveMeta, defoSlaveOrbit, topoSlaveMeta, topoSlaveOrbit); dinsar.setDataWindow(totalDataWindow); dinsar.computeBperpRatios(); dinsar.applyDInSAR(tileWindow, defoData, topoPhase); watch.stop(); logger.info("Total processing time: {} milli-seconds", watch.getTime()); ComplexDoubleMatrix expected = SarUtils.computeIfg(defoCplxIfg, defoData); int numOfElements = expected.length; double[] defoDelta = new double[numOfElements]; for (int i = 0; i < numOfElements; i++) { defoDelta[i] = Math.atan2(expected.getImag(i), expected.getReal(i)) * PHASE2DEFO; } Assert.assertArrayEquals(DoubleMatrix.zeros(defoCplxIfg.length).toArray(), defoDelta, DELTA_02); }
### Question: SLCImage { public double pix2tr(double pixel) { return tRange1 + ((pixel - 1.0) / rsr2x); } SLCImage(); SLCImage(MetadataElement element); void parseResFile(File resFileName); double pix2tr(double pixel); double pix2range(double pixel); double tr2pix(double rangeTime); double line2ta(double line); double ta2line(double azitime); Point lp2t(Point p); double getRadarWavelength(); Point getApproxRadarCentreOriginal(); GeoPoint getApproxGeoCentreOriginal(); Point getApproxXYZCentreOriginal(); void setCurrentWindow(final Window window); Window getCurrentWindow(); Window getOriginalWindow(); void setOriginalWindow(final Window window); double getPRF(); double getAzimuthBandwidth(); int getCoarseOffsetP(); double gettRange1(); void settRange1(double tRange1); double getRangeBandwidth(); void setRangeBandwidth(double rangeBandwidth); double getRsr2x(); void setRsr2x(double rsr2x); void setCoarseOffsetP(int offsetP); void setCoarseOffsetL(int offsetL); int getMlAz(); void setMlAz(int mlAz); int getMlRg(); void setMlRg(int mlRg); double getMjd(); long getOrbitNumber(); String getSensor(); String getMission(); int getOvsRg(); void setOvsRg(int ovsRg); void setSlaveMaterOffset(); SlaveWindow getSlaveMaterOffset(); void setSlaveMasterOffset(double ll00, double pp00, double ll0N, double pp0N, double llN0, double ppN0, double llNN, double ppNN); double computeDeltaRange(double pixel); double computeDeltaRange(Point sarPixel); double computeRangeResolution(double pixel); double computeRangeResolution(Point sarPixel); public Doppler doppler; }### Answer: @Test public void testPix2tr() throws Exception { double rgTime_ACTUAL = master.pix2tr(pixel_EXPECTED); Assert.assertEquals(rgTime_EXPECTED, rgTime_ACTUAL, eps05); }
### Question: SLCImage { public double tr2pix(double rangeTime) { return 1.0 + (rsr2x * (rangeTime - tRange1)); } SLCImage(); SLCImage(MetadataElement element); void parseResFile(File resFileName); double pix2tr(double pixel); double pix2range(double pixel); double tr2pix(double rangeTime); double line2ta(double line); double ta2line(double azitime); Point lp2t(Point p); double getRadarWavelength(); Point getApproxRadarCentreOriginal(); GeoPoint getApproxGeoCentreOriginal(); Point getApproxXYZCentreOriginal(); void setCurrentWindow(final Window window); Window getCurrentWindow(); Window getOriginalWindow(); void setOriginalWindow(final Window window); double getPRF(); double getAzimuthBandwidth(); int getCoarseOffsetP(); double gettRange1(); void settRange1(double tRange1); double getRangeBandwidth(); void setRangeBandwidth(double rangeBandwidth); double getRsr2x(); void setRsr2x(double rsr2x); void setCoarseOffsetP(int offsetP); void setCoarseOffsetL(int offsetL); int getMlAz(); void setMlAz(int mlAz); int getMlRg(); void setMlRg(int mlRg); double getMjd(); long getOrbitNumber(); String getSensor(); String getMission(); int getOvsRg(); void setOvsRg(int ovsRg); void setSlaveMaterOffset(); SlaveWindow getSlaveMaterOffset(); void setSlaveMasterOffset(double ll00, double pp00, double ll0N, double pp0N, double llN0, double ppN0, double llNN, double ppNN); double computeDeltaRange(double pixel); double computeDeltaRange(Point sarPixel); double computeRangeResolution(double pixel); double computeRangeResolution(Point sarPixel); public Doppler doppler; }### Answer: @Test public void testTr2pix() throws Exception { double pixel_ACTUAL = master.tr2pix(rgTime_EXPECTED); Assert.assertEquals(pixel_EXPECTED, pixel_ACTUAL, eps05); }
### Question: SLCImage { public double line2ta(double line) { return tAzi1 + ((line - 1.0) / PRF); } SLCImage(); SLCImage(MetadataElement element); void parseResFile(File resFileName); double pix2tr(double pixel); double pix2range(double pixel); double tr2pix(double rangeTime); double line2ta(double line); double ta2line(double azitime); Point lp2t(Point p); double getRadarWavelength(); Point getApproxRadarCentreOriginal(); GeoPoint getApproxGeoCentreOriginal(); Point getApproxXYZCentreOriginal(); void setCurrentWindow(final Window window); Window getCurrentWindow(); Window getOriginalWindow(); void setOriginalWindow(final Window window); double getPRF(); double getAzimuthBandwidth(); int getCoarseOffsetP(); double gettRange1(); void settRange1(double tRange1); double getRangeBandwidth(); void setRangeBandwidth(double rangeBandwidth); double getRsr2x(); void setRsr2x(double rsr2x); void setCoarseOffsetP(int offsetP); void setCoarseOffsetL(int offsetL); int getMlAz(); void setMlAz(int mlAz); int getMlRg(); void setMlRg(int mlRg); double getMjd(); long getOrbitNumber(); String getSensor(); String getMission(); int getOvsRg(); void setOvsRg(int ovsRg); void setSlaveMaterOffset(); SlaveWindow getSlaveMaterOffset(); void setSlaveMasterOffset(double ll00, double pp00, double ll0N, double pp0N, double llN0, double ppN0, double llNN, double ppNN); double computeDeltaRange(double pixel); double computeDeltaRange(Point sarPixel); double computeRangeResolution(double pixel); double computeRangeResolution(Point sarPixel); public Doppler doppler; }### Answer: @Test public void testLine2ta() throws Exception { double azTime_ACTUAL = master.line2ta(line_EXPECTED); Assert.assertEquals(azTime_EXPECTED, azTime_ACTUAL, eps05); }
### Question: SLCImage { public double ta2line(double azitime) { return 1.0 + PRF * (azitime - tAzi1); } SLCImage(); SLCImage(MetadataElement element); void parseResFile(File resFileName); double pix2tr(double pixel); double pix2range(double pixel); double tr2pix(double rangeTime); double line2ta(double line); double ta2line(double azitime); Point lp2t(Point p); double getRadarWavelength(); Point getApproxRadarCentreOriginal(); GeoPoint getApproxGeoCentreOriginal(); Point getApproxXYZCentreOriginal(); void setCurrentWindow(final Window window); Window getCurrentWindow(); Window getOriginalWindow(); void setOriginalWindow(final Window window); double getPRF(); double getAzimuthBandwidth(); int getCoarseOffsetP(); double gettRange1(); void settRange1(double tRange1); double getRangeBandwidth(); void setRangeBandwidth(double rangeBandwidth); double getRsr2x(); void setRsr2x(double rsr2x); void setCoarseOffsetP(int offsetP); void setCoarseOffsetL(int offsetL); int getMlAz(); void setMlAz(int mlAz); int getMlRg(); void setMlRg(int mlRg); double getMjd(); long getOrbitNumber(); String getSensor(); String getMission(); int getOvsRg(); void setOvsRg(int ovsRg); void setSlaveMaterOffset(); SlaveWindow getSlaveMaterOffset(); void setSlaveMasterOffset(double ll00, double pp00, double ll0N, double pp0N, double llN0, double ppN0, double llNN, double ppNN); double computeDeltaRange(double pixel); double computeDeltaRange(Point sarPixel); double computeRangeResolution(double pixel); double computeRangeResolution(Point sarPixel); public Doppler doppler; }### Answer: @Test public void testTa2line() throws Exception { double line_ACTUAL = master.ta2line(azTime_EXPECTED); Assert.assertEquals(line_EXPECTED, line_ACTUAL, eps02); }
### Question: SLCImage { public Point lp2t(Point p) { return new Point(pix2tr(p.x), line2ta(p.y)); } SLCImage(); SLCImage(MetadataElement element); void parseResFile(File resFileName); double pix2tr(double pixel); double pix2range(double pixel); double tr2pix(double rangeTime); double line2ta(double line); double ta2line(double azitime); Point lp2t(Point p); double getRadarWavelength(); Point getApproxRadarCentreOriginal(); GeoPoint getApproxGeoCentreOriginal(); Point getApproxXYZCentreOriginal(); void setCurrentWindow(final Window window); Window getCurrentWindow(); Window getOriginalWindow(); void setOriginalWindow(final Window window); double getPRF(); double getAzimuthBandwidth(); int getCoarseOffsetP(); double gettRange1(); void settRange1(double tRange1); double getRangeBandwidth(); void setRangeBandwidth(double rangeBandwidth); double getRsr2x(); void setRsr2x(double rsr2x); void setCoarseOffsetP(int offsetP); void setCoarseOffsetL(int offsetL); int getMlAz(); void setMlAz(int mlAz); int getMlRg(); void setMlRg(int mlRg); double getMjd(); long getOrbitNumber(); String getSensor(); String getMission(); int getOvsRg(); void setOvsRg(int ovsRg); void setSlaveMaterOffset(); SlaveWindow getSlaveMaterOffset(); void setSlaveMasterOffset(double ll00, double pp00, double ll0N, double pp0N, double llN0, double ppN0, double llNN, double ppNN); double computeDeltaRange(double pixel); double computeDeltaRange(Point sarPixel); double computeRangeResolution(double pixel); double computeRangeResolution(Point sarPixel); public Doppler doppler; }### Answer: @Test public void testLp2t() throws Exception { final Point sarPoint = new Point(pixel_EXPECTED, line_EXPECTED); final Point timePoint = master.lp2t(sarPoint); Assert.assertEquals(rgTime_EXPECTED, timePoint.x, eps05); Assert.assertEquals(azTime_EXPECTED, timePoint.y, eps05); }
### Question: SLCImage { public double computeDeltaRange(double pixel) { return mlRg * (pix2range(pixel + 1) - pix2range(pixel)); } SLCImage(); SLCImage(MetadataElement element); void parseResFile(File resFileName); double pix2tr(double pixel); double pix2range(double pixel); double tr2pix(double rangeTime); double line2ta(double line); double ta2line(double azitime); Point lp2t(Point p); double getRadarWavelength(); Point getApproxRadarCentreOriginal(); GeoPoint getApproxGeoCentreOriginal(); Point getApproxXYZCentreOriginal(); void setCurrentWindow(final Window window); Window getCurrentWindow(); Window getOriginalWindow(); void setOriginalWindow(final Window window); double getPRF(); double getAzimuthBandwidth(); int getCoarseOffsetP(); double gettRange1(); void settRange1(double tRange1); double getRangeBandwidth(); void setRangeBandwidth(double rangeBandwidth); double getRsr2x(); void setRsr2x(double rsr2x); void setCoarseOffsetP(int offsetP); void setCoarseOffsetL(int offsetL); int getMlAz(); void setMlAz(int mlAz); int getMlRg(); void setMlRg(int mlRg); double getMjd(); long getOrbitNumber(); String getSensor(); String getMission(); int getOvsRg(); void setOvsRg(int ovsRg); void setSlaveMaterOffset(); SlaveWindow getSlaveMaterOffset(); void setSlaveMasterOffset(double ll00, double pp00, double ll0N, double pp0N, double llN0, double ppN0, double llNN, double ppNN); double computeDeltaRange(double pixel); double computeDeltaRange(Point sarPixel); double computeRangeResolution(double pixel); double computeRangeResolution(Point sarPixel); public Doppler doppler; }### Answer: @Test public void testComputeDeltaRange() throws Exception { Assert.assertEquals(deltaRange_EXPECTED, master.computeDeltaRange(CORNER_REFLECTOR_4), eps05); }
### Question: SLCImage { public double computeRangeResolution(double pixel) { return ((rsr2x / 2.) / rangeBandwidth) * (computeDeltaRange(pixel) / mlRg); } SLCImage(); SLCImage(MetadataElement element); void parseResFile(File resFileName); double pix2tr(double pixel); double pix2range(double pixel); double tr2pix(double rangeTime); double line2ta(double line); double ta2line(double azitime); Point lp2t(Point p); double getRadarWavelength(); Point getApproxRadarCentreOriginal(); GeoPoint getApproxGeoCentreOriginal(); Point getApproxXYZCentreOriginal(); void setCurrentWindow(final Window window); Window getCurrentWindow(); Window getOriginalWindow(); void setOriginalWindow(final Window window); double getPRF(); double getAzimuthBandwidth(); int getCoarseOffsetP(); double gettRange1(); void settRange1(double tRange1); double getRangeBandwidth(); void setRangeBandwidth(double rangeBandwidth); double getRsr2x(); void setRsr2x(double rsr2x); void setCoarseOffsetP(int offsetP); void setCoarseOffsetL(int offsetL); int getMlAz(); void setMlAz(int mlAz); int getMlRg(); void setMlRg(int mlRg); double getMjd(); long getOrbitNumber(); String getSensor(); String getMission(); int getOvsRg(); void setOvsRg(int ovsRg); void setSlaveMaterOffset(); SlaveWindow getSlaveMaterOffset(); void setSlaveMasterOffset(double ll00, double pp00, double ll0N, double pp0N, double llN0, double ppN0, double llNN, double ppNN); double computeDeltaRange(double pixel); double computeDeltaRange(Point sarPixel); double computeRangeResolution(double pixel); double computeRangeResolution(Point sarPixel); public Doppler doppler; }### Answer: @Test public void testComputeRangeResolution() throws Exception { Assert.assertEquals(rangeResolution_EXPECTED, master.computeRangeResolution(CORNER_REFLECTOR_4), eps05); }
### Question: CrossGeometry { public void computeCoeffsFromOffsets() { constructGrids(); DoubleMatrix sourceY = new DoubleMatrix(numberOfWindows, 1); DoubleMatrix sourceX = new DoubleMatrix(numberOfWindows, 1); DoubleMatrix offsetY = new DoubleMatrix(numberOfWindows, 1); DoubleMatrix offsetX = new DoubleMatrix(numberOfWindows, 1); for (int i = 0; i < numberOfWindows; i++) { if (normalizeFlag) { sourceY.put(i, PolyUtils.normalize2(sourceGrid[i][0], dataWindow.linelo, dataWindow.linehi)); sourceX.put(i, PolyUtils.normalize2(sourceGrid[i][1], dataWindow.pixlo, dataWindow.pixhi)); } else { sourceY.put(i, sourceGrid[i][0]); sourceX.put(i, sourceGrid[i][1]); } offsetY.put(i, offsetGrid[i][0]); offsetX.put(i, offsetGrid[i][1]); } coeffsAz = PolyUtils.polyFit2D(sourceX, sourceY, offsetY, polyDegree); coeffsRg = PolyUtils.polyFit2D(sourceX, sourceY, offsetX, polyDegree); logger.debug("coeffsAZ (offsets): estimated with PolyUtils.polyFit2D : {}", ArrayUtils.toString(coeffsAz)); logger.debug("coeffsRg (offsets): estimated with PolyUtils.polyFit2D : {}", ArrayUtils.toString(coeffsRg)); } CrossGeometry(); CrossGeometry(double prfOriginal, double prfTarget, double rsrOriginal, double rsrSlave, Window window); CrossGeometry(SLCImage masterMeta, SLCImage slaveMeta); int getNumberOfWindows(); void setNumberOfWindows(int numberOfWindows); void setDataWindow(Window dataWindow); void setPrfOriginal(double prfOriginal); void setPrfTarget(double prfTarget); void setRsrOriginal(double rsrOriginal); void setRsrTarget(double rsrTarget); int getPolyDegree(); void setPolyDegree(int polyDegree); double getRatioPRF(); double getRatioRSR(); double[] getCoeffsAz(); double[] getCoeffsRg(); double[][] getSourceGrid(); double[][] getTargetGrid(); double[][] getOffsetGrid(); void setNormalizeFlag(boolean normalizeFlag); void constructGrids(); void computeCoeffsFromOffsets(); void computeCoeffsFromCoords_JAI(); }### Answer: @Test public void testComputeCoeffsFromOffsets() { CrossGeometry crossGeometry = new CrossGeometry(); crossGeometry.setPrfOriginal(prfERS); crossGeometry.setRsrOriginal(rsrERS); crossGeometry.setPrfTarget(prfASAR); crossGeometry.setRsrTarget(rsrASAR); crossGeometry.setDataWindow(new Window(lineLo, lineHi, pixelLo, pixelHi)); crossGeometry.setNumberOfWindows(NUM_OF_WINDOWS); crossGeometry.setPolyDegree(POLY_DEGREE); crossGeometry.setNormalizeFlag(true); crossGeometry.computeCoeffsFromOffsets(); double[] coeffsAz = crossGeometry.getCoeffsAz(); double[] coeffsRg = crossGeometry.getCoeffsRg(); logger.debug("coeffsAZ (from offsets): estimated with PolyUtils.polyFit2D : {}", ArrayUtils.toString(coeffsAz)); logger.debug("coeffsRg (from offsets): estimated with PolyUtils.polyFit2D : {}", ArrayUtils.toString(coeffsRg)); logger.debug("-----"); }
### Question: GeoUtils { public static GeoPoint[] computeCorners(final SLCImage meta, final Orbit orbit, final Window tile, final float height[]) throws Exception { if (height.length != 4) { throw new IllegalArgumentException("input height array has to have 4 elements"); } GeoPoint[] corners = new GeoPoint[2]; double[] phiAndLambda; final double l0 = tile.linelo; final double lN = tile.linehi; final double p0 = tile.pixlo; final double pN = tile.pixhi; phiAndLambda = orbit.lph2ell(new Point(p0, l0, height[0]), meta); final double phi_l0p0 = phiAndLambda[0]; final double lambda_l0p0 = phiAndLambda[1]; phiAndLambda = orbit.lp2ell(new Point(p0, lN, height[1]), meta); final double phi_lNp0 = phiAndLambda[0]; final double lambda_lNp0 = phiAndLambda[1]; phiAndLambda = orbit.lp2ell(new Point(pN, lN, height[2]), meta); final double phi_lNpN = phiAndLambda[0]; final double lambda_lNpN = phiAndLambda[1]; phiAndLambda = orbit.lp2ell(new Point(pN, l0, height[3]), meta); final double phi_l0pN = phiAndLambda[0]; final double lambda_l0pN = phiAndLambda[1]; double phiMin = Math.min(Math.min(Math.min(phi_l0p0, phi_lNp0), phi_lNpN), phi_l0pN); double phiMax = Math.max(Math.max(Math.max(phi_l0p0, phi_lNp0), phi_lNpN), phi_l0pN); double lambdaMin = Math.min(Math.min(Math.min(lambda_l0p0, lambda_lNp0), lambda_lNpN), lambda_l0pN); double lambdaMax = Math.max(Math.max(Math.max(lambda_l0p0, lambda_lNp0), lambda_lNpN), lambda_l0pN); corners[0] = new GeoPoint((float) (phiMax * Constants.RTOD), (float) (lambdaMin * Constants.RTOD)); corners[1] = new GeoPoint((float) (phiMin * Constants.RTOD), (float) (lambdaMax * Constants.RTOD)); return corners; } static GeoPoint[] computeCorners(final SLCImage meta, final Orbit orbit, final Window tile, final float height[]); static GeoPoint[] computeCorners(final SLCImage meta, final Orbit orbit, final Window tile); static GeoPoint[] extendCorners(final GeoPoint extraGeo, final GeoPoint[] inGeo); synchronized static GeoPoint defineExtraPhiLam(final double heightMin, final double heightMax, final Window window, final SLCImage meta, final Orbit orbit); @Deprecated static GeoPoint[] computeCorners(final SLCImage meta, final Orbit orbit, final Window tile, final double phiExtra, final double lambdaExtra); @Deprecated static GeoPoint defineExtraPhiLam(double latDelta, double lonDelta); }### Answer: @Ignore @Test public void testComputeCorners() throws Exception { long start = System.currentTimeMillis(); GeoPoint[] corners = GeoUtils.computeCorners(slcimage, orbit_ACTUAL, window, height); long stop = System.currentTimeMillis(); System.out.println("time = " + (double)(stop - start)/1000); Assert.assertEquals(corners[0].getLat(), latMax_ACTUAL, eps_04); Assert.assertEquals(corners[1].getLat(), latMin_ACTUAL, eps_04); Assert.assertEquals(corners[0].getLon(), lonMin_ACTUAL, eps_04); Assert.assertEquals(corners[1].getLon(), lonMax_ACTUAL, eps_04); }
### Question: TimeData implements RowData<T> { @NonNull @Override public ContentProviderOperation.Builder updatedBuilder(@NonNull TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder) { if (mDue.isPresent() && mStart.isAllDay() != mDue.value().isAllDay()) { throw new IllegalArgumentException("'start' and 'due' must have the same all-day flag"); } DateTime start = mStart; if (mDue.isPresent() && !mDue.value().isAllDay()) { start = mStart.shiftTimeZone(mDue.value().getTimeZone()); } return doUpdateBuilder(start, mDue, mDuration, builder); } private TimeData(@NonNull DateTime start, @NonNull Optional<DateTime> due, @NonNull Optional<Duration> duration); TimeData(@NonNull DateTime start, @NonNull DateTime due); TimeData(@NonNull DateTime start, @NonNull Duration duration); TimeData(@NonNull DateTime start); @NonNull @Override ContentProviderOperation.Builder updatedBuilder(@NonNull TransactionContext transactionContext, @NonNull ContentProviderOperation.Builder builder); }### Answer: @Test(expected = IllegalArgumentException.class) public void test_whenStartIsAllDayAndDueIsNot_throwsIllegalArgument() { new TimeData<>(DateTime.now().toAllDay(), DateTime.now()) .updatedBuilder(mock(TransactionContext.class), mock(ContentProviderOperation.Builder.class)); } @Test(expected = IllegalArgumentException.class) public void test_whenDueIsAllDayAndStartIsNot_throwsIllegalArgument() { new TimeData<>(DateTime.now(), DateTime.now().toAllDay()) .updatedBuilder(mock(TransactionContext.class), mock(ContentProviderOperation.Builder.class)); }
### Question: Overridden implements Single<ContentValues> { @Override public ContentValues value() { ContentValues values = mDelegate.value(); values.put(TaskContract.Instances.INSTANCE_ORIGINAL_TIME, new Backed<Long>( new FirstPresent<>( new Seq<>( new Mapped<>(DateTime::getTimestamp, mOriginalTime), new NullSafe<>(values.getAsLong(TaskContract.Instances.INSTANCE_START)), new NullSafe<>(values.getAsLong(TaskContract.Instances.INSTANCE_DUE)))), () -> null).value()); return values; } Overridden(Optional<DateTime> originalTime, Single<ContentValues> delegate); @Override ContentValues value(); }### Answer: @Test public void testAbsentWithStartAndDue() { ContentValues values = new ContentValues(); values.put(TaskContract.Instances.INSTANCE_START, 10); values.put(TaskContract.Instances.INSTANCE_DUE, 20); ContentValues instanceData = new Overridden(absent(), () -> new ContentValues(values)).value(); assertThat(instanceData, new ContentValuesWithLong(TaskContract.Instances.INSTANCE_ORIGINAL_TIME, 10)); assertThat(instanceData.size(), is(3)); } @Test public void testPresent() { ContentValues instanceData = new Overridden(new Present<>(new DateTime(40)), ContentValues::new).value(); assertThat(instanceData, new ContentValuesWithLong(TaskContract.Instances.INSTANCE_ORIGINAL_TIME, 40)); assertThat(instanceData.size(), is(1)); } @Test public void testPresentWithStartAndDue() { ContentValues values = new ContentValues(); values.put(TaskContract.Instances.INSTANCE_START, 10); values.put(TaskContract.Instances.INSTANCE_DUE, 20); ContentValues instanceData = new Overridden(new Present<>(new DateTime(40)), () -> new ContentValues(values)).value(); assertThat(instanceData, new ContentValuesWithLong(TaskContract.Instances.INSTANCE_ORIGINAL_TIME, 40)); assertThat(instanceData.size(), is(3)); } @Test public void testAbsent() { ContentValues instanceData = new Overridden(absent(), ContentValues::new).value(); assertThat(instanceData, new ContentValuesWithLong(TaskContract.Instances.INSTANCE_ORIGINAL_TIME, nullValue(Long.class))); assertThat(instanceData.size(), is(1)); } @Test public void testAbsentWithStart() { ContentValues values = new ContentValues(); values.put(TaskContract.Instances.INSTANCE_START, 10); ContentValues instanceData = new Overridden(absent(), () -> new ContentValues(values)).value(); assertThat(instanceData, new ContentValuesWithLong(TaskContract.Instances.INSTANCE_ORIGINAL_TIME, 10)); assertThat(instanceData.size(), is(2)); } @Test public void testAbsentWithDue() { ContentValues values = new ContentValues(); values.put(TaskContract.Instances.INSTANCE_DUE, 20); ContentValues instanceData = new Overridden(absent(), () -> new ContentValues(values)).value(); assertThat(instanceData, new ContentValuesWithLong(TaskContract.Instances.INSTANCE_ORIGINAL_TIME, 20)); assertThat(instanceData.size(), is(2)); }
### Question: Enduring implements Single<ContentValues> { @Override public ContentValues value() { ContentValues values = mDelegate.value(); values.put(TaskContract.Instances.INSTANCE_DURATION, new Backed<Long>( new Zipped<>( new NullSafe<>(values.getAsLong(TaskContract.Instances.INSTANCE_START)), new NullSafe<>(values.getAsLong(TaskContract.Instances.INSTANCE_DUE)), (start, due) -> due - start), () -> null).value()); return values; } Enduring(Single<ContentValues> delegate); @Override ContentValues value(); }### Answer: @Test public void testNoValue() { assertThat(new Enduring(ContentValues::new), hasValue(new ContentValuesWithLong(TaskContract.Instances.INSTANCE_DURATION, nullValue(Long.class)))); assertThat(new Enduring(ContentValues::new).value().size(), is(1)); } @Test public void testStartValue() { ContentValues values = new ContentValues(1); values.put(TaskContract.Instances.INSTANCE_START, 10); assertThat(new Enduring(() -> new ContentValues(values)), hasValue(new ContentValuesWithLong(TaskContract.Instances.INSTANCE_DURATION, nullValue(Long.class)))); assertThat(new Enduring(() -> new ContentValues(values)).value().size(), is(2)); } @Test public void testDueValue() { ContentValues values = new ContentValues(1); values.put(TaskContract.Instances.INSTANCE_DUE, 10); assertThat(new Enduring(() -> new ContentValues(values)), hasValue(new ContentValuesWithLong(TaskContract.Instances.INSTANCE_DURATION, nullValue(Long.class)))); assertThat(new Enduring(() -> new ContentValues(values)).value().size(), is(2)); } @Test public void testStartDueValue() { ContentValues values = new ContentValues(2); values.put(TaskContract.Instances.INSTANCE_START, 1); values.put(TaskContract.Instances.INSTANCE_DUE, 10); assertThat(new Enduring(() -> new ContentValues(values)), hasValue(new ContentValuesWithLong(TaskContract.Instances.INSTANCE_DURATION, 9))); assertThat(new Enduring(() -> new ContentValues(values)).value().size(), is(3)); }
### Question: DateTimeIterableFieldAdapter extends SimpleFieldAdapter<Iterable<DateTime>, EntityType> { @Override String fieldName() { return mDateTimeListFieldName; } DateTimeIterableFieldAdapter(String datetimeListFieldName, String timezoneFieldName); @Override Iterable<DateTime> getFrom(ContentValues values); @Override Iterable<DateTime> getFrom(Cursor cursor); @Override Iterable<DateTime> getFrom(Cursor cursor, ContentValues values); @Override void setIn(ContentValues values, Iterable<DateTime> value); }### Answer: @Test public void testFieldName() { assertThat(new DateTimeIterableFieldAdapter<>("x", "y").fieldName(), is("x")); }
### Question: DateTimeIterableFieldAdapter extends SimpleFieldAdapter<Iterable<DateTime>, EntityType> { @Override public Iterable<DateTime> getFrom(ContentValues values) { String datetimeList = values.getAsString(mDateTimeListFieldName); if (datetimeList == null) { return EmptyIterable.instance(); } String timezoneString = mTimeZoneFieldName == null ? null : values.getAsString(mTimeZoneFieldName); TimeZone timeZone = timezoneString == null ? null : TimeZone.getTimeZone(timezoneString); return new DateTimeList(timeZone, datetimeList); } DateTimeIterableFieldAdapter(String datetimeListFieldName, String timezoneFieldName); @Override Iterable<DateTime> getFrom(ContentValues values); @Override Iterable<DateTime> getFrom(Cursor cursor); @Override Iterable<DateTime> getFrom(Cursor cursor, ContentValues values); @Override void setIn(ContentValues values, Iterable<DateTime> value); }### Answer: @Test public void testGetFromCVAllDay1() { ContentValues values = new ContentValues(); FieldAdapter<Iterable<DateTime>, ?> adapter = new DateTimeIterableFieldAdapter<TaskAdapter>("x", "y"); values.put("x", "20180109"); assertThat(adapter.getFrom(values), iteratesTo(DateTime.parse("20180109"))); } @Test public void testGetFromCVAllDay2() { ContentValues values = new ContentValues(); FieldAdapter<Iterable<DateTime>, ?> adapter = new DateTimeIterableFieldAdapter<TaskAdapter>("x", "y"); values.put("x", "20180109,20180110"); assertThat(adapter.getFrom(values), iteratesTo(DateTime.parse("20180109"), DateTime.parse("20180110"))); } @Test public void testGetFromCVFloating1() { ContentValues values = new ContentValues(); FieldAdapter<Iterable<DateTime>, ?> adapter = new DateTimeIterableFieldAdapter<TaskAdapter>("x", "y"); values.put("x", "20180109T140000"); values.putNull("y"); assertThat(adapter.getFrom(values), iteratesTo(DateTime.parse("20180109T140000"))); } @Test public void testGetFromCVFloating2() { ContentValues values = new ContentValues(); FieldAdapter<Iterable<DateTime>, ?> adapter = new DateTimeIterableFieldAdapter<TaskAdapter>("x", "y"); values.put("x", "20180109T140000,20180110T140000"); values.putNull("y"); assertThat(adapter.getFrom(values), iteratesTo(DateTime.parse("20180109T140000"), DateTime.parse("20180110T140000"))); } @Test public void testGetFromCVAbsolute1() { ContentValues values = new ContentValues(); FieldAdapter<Iterable<DateTime>, ?> adapter = new DateTimeIterableFieldAdapter<TaskAdapter>("x", "y"); values.put("x", "20180109T140000Z"); values.put("y", "Europe/Berlin"); assertThat(adapter.getFrom(values), iteratesTo(DateTime.parse("Europe/Berlin", "20180109T150000"))); } @Test public void testGetFromCVAbsolute2() { ContentValues values = new ContentValues(); FieldAdapter<Iterable<DateTime>, ?> adapter = new DateTimeIterableFieldAdapter<TaskAdapter>("x", "y"); values.put("x", "20180109T140000Z,20180110T140000Z"); values.put("y", "Europe/Berlin"); assertThat(adapter.getFrom(values), iteratesTo(DateTime.parse("Europe/Berlin", "20180109T150000"), DateTime.parse("Europe/Berlin", "20180110T150000"))); }
### Question: Toggled implements NotificationSignal { @Override public int value() { if (mFlag != Notification.DEFAULT_VIBRATE && mFlag != Notification.DEFAULT_SOUND && mFlag != Notification.DEFAULT_LIGHTS) { throw new IllegalArgumentException("Notification signal flag is not valid: " + mFlag); } return mEnable ? addFlag(mOriginal.value(), mFlag) : removeFlag(mOriginal.value(), mFlag); } Toggled(int flag, boolean enable, NotificationSignal original); @Override int value(); }### Answer: @Test public void testValidFlags_dontThrowException() { new Toggled(Notification.DEFAULT_SOUND, true, new NoSignal()).value(); new Toggled(Notification.DEFAULT_VIBRATE, true, new NoSignal()).value(); new Toggled(Notification.DEFAULT_LIGHTS, true, new NoSignal()).value(); } @Test(expected = IllegalArgumentException.class) public void testInValidFlag_throwsException() { new Toggled(15, true, new NoSignal()).value(); } @Test public void testAddingFlag() { assertThat(new Toggled(Notification.DEFAULT_SOUND, true, new NoSignal()).value(), is(new NoSignal().value() | Notification.DEFAULT_SOUND)); assertThat(new Toggled(Notification.DEFAULT_SOUND, false, new NoSignal()).value(), is(new NoSignal().value())); }
### Question: ContainsValues implements Predicate<Cursor> { @Override public boolean satisfiedBy(Cursor testedInstance) { for (String key : mValues.keySet()) { int columnIdx = testedInstance.getColumnIndex(key); if (columnIdx < 0) { return false; } if (testedInstance.getType(columnIdx) == Cursor.FIELD_TYPE_BLOB) { if (!Arrays.equals(mValues.getAsByteArray(key), testedInstance.getBlob(columnIdx))) { return false; } } else { String stringValue = mValues.getAsString(key); if (stringValue != null && !stringValue.equals(testedInstance.getString(columnIdx)) || stringValue == null && !testedInstance.isNull(columnIdx)) { return false; } } } return true; } ContainsValues(ContentValues values); @Override boolean satisfiedBy(Cursor testedInstance); }### Answer: @Test public void test() { ContentValues values = new ContentValues(); values.put("a", 123); values.put("b", "stringValue"); values.put("c", new byte[] { 3, 2, 1 }); values.putNull("d"); MatrixCursor cursor = new MatrixCursor(new String[] { "c", "b", "a", "d", "f" }); cursor.addRow(new Seq<>(new byte[] { 3, 2, 1 }, "stringValue", 123, null, "xyz")); cursor.addRow(new Seq<>(new byte[] { 3, 2, 1 }, "stringValue", "123", null, "xyz")); cursor.addRow(new Seq<>(new byte[] { 3, 2 }, "stringValue", 123, null, "xyz")); cursor.addRow(new Seq<>(new byte[] { 3, 2, 1 }, "stringValueX", 123, null, "xyz")); cursor.addRow(new Seq<>(new byte[] { 3, 2, 1 }, "stringValue", 1234, null, "xyz")); cursor.addRow(new Seq<>(new byte[] { 3, 2, 1 }, "stringValue", 123, "123", "xyz")); cursor.addRow(new Seq<>(321, "stringValueX", "1234", "123", "xyz")); cursor.addRow(new Seq<>(new byte[] { 3, 2, 1, 0 }, "stringValueX", 1234, "123", "xyz")); cursor.moveToFirst(); assertThat(new ContainsValues(values), is(satisfiedBy(cursor))); cursor.moveToNext(); assertThat(new ContainsValues(values), is(satisfiedBy(cursor))); cursor.moveToNext(); assertThat(new ContainsValues(values), is(not(satisfiedBy(cursor)))); cursor.moveToNext(); assertThat(new ContainsValues(values), is(not(satisfiedBy(cursor)))); cursor.moveToNext(); assertThat(new ContainsValues(values), is(not(satisfiedBy(cursor)))); cursor.moveToNext(); assertThat(new ContainsValues(values), is(not(satisfiedBy(cursor)))); cursor.moveToNext(); assertThat(new ContainsValues(values), is(not(satisfiedBy(cursor)))); cursor.moveToNext(); assertThat(new ContainsValues(values), is(not(satisfiedBy(cursor)))); } @Test public void testMissingColumns() { ContentValues values = new ContentValues(); values.put("a", 123); values.put("b", "stringValue"); values.put("c", new byte[] { 3, 2, 1 }); values.putNull("d"); MatrixCursor cursor = new MatrixCursor(new String[] { "c", "b" }); cursor.addRow(new Seq<>(new byte[] { 3, 2, 1 }, "stringValue")); cursor.moveToFirst(); assertThat(new ContainsValues(values), is(not(satisfiedBy(cursor)))); }
### Question: VanillaInstanceData implements Single<ContentValues> { @Override public ContentValues value() { ContentValues values = new ContentValues(6); values.putNull(TaskContract.Instances.INSTANCE_START); values.putNull(TaskContract.Instances.INSTANCE_START_SORTING); values.putNull(TaskContract.Instances.INSTANCE_DUE); values.putNull(TaskContract.Instances.INSTANCE_DUE_SORTING); values.putNull(TaskContract.Instances.INSTANCE_DURATION); values.put(TaskContract.Instances.DISTANCE_FROM_CURRENT, 0); values.putNull(TaskContract.Instances.INSTANCE_ORIGINAL_TIME); return values; } @Override ContentValues value(); }### Answer: @Test public void testValue() { ContentValues values = new VanillaInstanceData().value(); assertThat(values.get(TaskContract.Instances.INSTANCE_START), nullValue()); assertThat(values.get(TaskContract.Instances.INSTANCE_START_SORTING), nullValue()); assertThat(values.get(TaskContract.Instances.INSTANCE_DUE), nullValue()); assertThat(values.get(TaskContract.Instances.INSTANCE_DUE_SORTING), nullValue()); assertThat(values.get(TaskContract.Instances.INSTANCE_DURATION), nullValue()); assertThat(values.get(TaskContract.Instances.DISTANCE_FROM_CURRENT), is(0)); assertThat(values.get(TaskContract.Instances.INSTANCE_ORIGINAL_TIME), nullValue()); assertThat(values.size(), is(7)); }
### Question: TaskRelated implements Single<ContentValues> { @Override public ContentValues value() { ContentValues values = mDelegate.value(); values.put(TaskContract.Instances.TASK_ID, mTaskId); return values; } TaskRelated(long taskId, Single<ContentValues> delegate); @Override ContentValues value(); }### Answer: @Test public void testValue() { assertThat(new TaskRelated(123, ContentValues::new), hasValue(new ContentValuesWithLong(TaskContract.Instances.TASK_ID, 123))); }
### Question: MavenScm { public boolean isEmpty() { return this.connection == null && this.developerConnection == null && this.tag == null && this.url == null; } MavenScm(Builder builder); boolean isEmpty(); String getConnection(); String getDeveloperConnection(); String getTag(); String getUrl(); }### Answer: @Test void isEmptyWithNoData() { MavenScm mavenScm = new MavenScm.Builder().build(); assertThat(mavenScm.isEmpty()).isTrue(); } @Test void isEmptyWithData() { MavenScm mavenScm = new MavenScm.Builder().connection("some-connection").build(); assertThat(mavenScm.isEmpty()).isFalse(); }
### Question: MyFirstActor extends AbstractActor { static public Props props() { return Props.create(MyFirstActor.class, () -> new MyFirstActor()); } static Props props(); @Override Receive createReceive(); }### Answer: @Test public void testMyFirstActor_Greeting() { final TestKit probe = new TestKit(actorSystem); final ActorRef myFirstActor = actorSystem.actorOf(MyFirstActor.props()); myFirstActor.tell(new Greeting(HELLO_WORLD), probe.getRef()); final Greeting greeting = probe.expectMsgClass(Greeting.class); assertEquals(HELLO_WORLD, greeting.getMessage()); }
### Question: Calculator implements ICalculator { @Override public String add(int... values) { int sum = 0; for (int value : values) { sum += value; } return format(sum); } @Override String add(int... values); @Override String multiply(int... values); @Override String evaluate(String value); }### Answer: @Test public void testAdd() { assertEquals("3", mCalculator.evaluate(Matchers.anyString())); final String result = mCalculator.add(1,2); assertEquals("3", result); when(mCalculator.evaluate(Matchers.anyString())).thenReturn("5"); assertEquals("5", mCalculator.evaluate(Matchers.anyString())); }
### Question: CalcApi { public String getEvaluateSumUrl(final int a, final int b) { return getEvaluateUrl(a + "+" + b); } CalcApi(final String pBasePath); String getEvaluateSumUrl(final int a, final int b); String getEvaluateUrl(String input); }### Answer: @Test public void calculateSum() throws Exception { assertEquals(BASE_PATH + "/" + "calc?input=1%2B15", mCalcApi.getEvaluateSumUrl(1, 15)); }
### Question: CalcApi { public String getEvaluateUrl(String input) { try { return mBasePath + CALC + URLEncoder.encode(input, "UTF-8"); } catch (final UnsupportedEncodingException pE) { throw new IllegalStateException(pE); } } CalcApi(final String pBasePath); String getEvaluateSumUrl(final int a, final int b); String getEvaluateUrl(String input); }### Answer: @Test public void evaluate() throws Exception { assertEquals(BASE_PATH + "/" + "calc?input=I%27m+lucky", mCalcApi.getEvaluateUrl("I'm lucky")); }
### Question: ExcludeFilter implements ArtifactsFilter { @Override public boolean isArtifactIncluded(final Artifact artifact) throws ArtifactFilterException { return !(artifact.getGroupId().equals(excludedGroupId) && artifact.getArtifactId().equals(excludedArtifactId)); } ExcludeFilter(final String excludedGroupId, final String excludedArtifactId); @Override Set<Artifact> filter(final Set<Artifact> artifacts); @Override boolean isArtifactIncluded(final Artifact artifact); }### Answer: @Test public void shouldExcludeByGroupAndArtifactId() throws ArtifactFilterException { assertThat(filter.isArtifactIncluded(excluded)).isFalse(); assertThat(filter.isArtifactIncluded(included1)).isTrue(); assertThat(filter.isArtifactIncluded(included2)).isTrue(); }
### Question: SpecificationResourceCustomizer implements ComponentProxyCustomizer { @Override public void customize(final ComponentProxyComponent component, final Map<String, Object> options) { if (options.containsKey(ComponentProperties.WSDL_URL)) { options.remove(ComponentProperties.SPECIFICATION); } else if (options.containsKey(ComponentProperties.SPECIFICATION)) { consumeOption(options, ComponentProperties.SPECIFICATION, specificationObject -> { final String specification = (String) specificationObject; try { final File tempSpecification = File.createTempFile("soap", ".wsdl"); tempSpecification.deleteOnExit(); final String wsdlURL = tempSpecification.getAbsolutePath(); try (OutputStream out = new FileOutputStream(wsdlURL)) { IOUtils.write(specification, out, StandardCharsets.UTF_8); } options.put(ComponentProperties.WSDL_URL, wsdlURL); } catch (final IOException e) { throw new IllegalStateException("Unable to persist the WSDL specification to filesystem", e); } }); } else { throw new IllegalStateException("Missing property, either 'wsdlURL' or 'specification' MUST be provided"); } } @Override void customize(final ComponentProxyComponent component, final Map<String, Object> options); }### Answer: @Test public void shouldThrowExceptionOnMissingProperties() { final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer(); final Map<String, Object> options = new HashMap<>(); assertThrows(IllegalStateException.class, () -> customizer.customize(NOT_USED, options)); } @Test public void shouldStoreSpecificationInTemporaryDirectory() { final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer(); final Map<String, Object> options = new HashMap<>(); options.put(SPECIFICATION, CONTENTS); customizer.customize(NOT_USED, options); assertThat(options).containsKey(WSDL_URL); assertThat(options).doesNotContainKey(SPECIFICATION); assertThat(new File(ConnectorOptions.extractOption(options, WSDL_URL))).hasContent(CONTENTS); } @Test public void shouldIgnoreSpecificationWhenWsdlUrlIsPresent() { final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer(); final Map<String, Object> options = new HashMap<>(); options.put(SPECIFICATION, CONTENTS); options.put(WSDL_URL, HTTP_DUMMY_URL); customizer.customize(NOT_USED, options); assertThat(options).containsKey(WSDL_URL); assertThat(options.get(WSDL_URL)).isEqualTo(HTTP_DUMMY_URL); assertThat(options).doesNotContainKey(SPECIFICATION); }
### Question: EndpointCustomizer implements ComponentProxyCustomizer { @Override public void customize(final ComponentProxyComponent component, final Map<String, Object> options) { consumeOption(options, SERVICE_NAME, serviceObject -> { final String serviceName = (String) serviceObject; final QName service = QName.valueOf(serviceName); options.put(SERVICE_NAME, serviceName); consumeOption(options, ComponentProperties.PORT_NAME, portObject -> { final QName port = new QName(service.getNamespaceURI(), (String) portObject); options.put(ComponentProperties.PORT_NAME, port.toString()); }); }); } @Override void customize(final ComponentProxyComponent component, final Map<String, Object> options); }### Answer: @Test public void shouldAddEndpointName() { final EndpointCustomizer customizer = new EndpointCustomizer(); final Map<String, Object> options = new HashMap<>(); options.put(ComponentProperties.SERVICE_NAME, "{namespace}service1"); options.put(ComponentProperties.PORT_NAME, "port1"); customizer.customize(NOT_USED, options); assertThat(options).containsKeys("serviceName", "portName"); assertThat(ConnectorOptions.extractOption(options, "serviceName")).isEqualTo("{namespace}service1"); assertThat(ConnectorOptions.extractOption(options, "portName")).isEqualTo("{namespace}port1"); }
### Question: BoxVerifierExtension extends DefaultComponentVerifierExtension { @Override protected Result verifyParameters(Map<String, Object> parameters) { ResultBuilder builder = ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.PARAMETERS) .error(ResultErrorHelper.requiresOption("userName", parameters)) .error(ResultErrorHelper.requiresOption("userPassword", parameters)) .error(ResultErrorHelper.requiresOption("clientId", parameters)) .error(ResultErrorHelper.requiresOption("clientSecret", parameters)); return builder.build(); } protected BoxVerifierExtension(String defaultScheme, CamelContext context); }### Answer: @Test public void verifyParameters() { Result result = verifier.verifyParameters(parameters); assertEquals(errorDescriptions(result), Result.Status.OK, result.getStatus()); }
### Question: BoxVerifierExtension extends DefaultComponentVerifierExtension { @Override protected Result verifyConnectivity(Map<String, Object> parameters) { return ResultBuilder.withStatusAndScope(Result.Status.OK, Scope.CONNECTIVITY) .error(parameters, this::verifyCredentials).build(); } protected BoxVerifierExtension(String defaultScheme, CamelContext context); }### Answer: @Test public void verifyConnectivity() { Result result = verifier.verifyConnectivity(parameters); assertEquals(errorDescriptions(result), Result.Status.OK, result.getStatus()); }
### Question: BoxDownloadCustomizer implements ComponentProxyCustomizer { private void afterProducer(Exchange exchange) { BoxFile file = new BoxFile(); Message in = exchange.getIn(); file.setId(fileId); ByteArrayOutputStream output = in.getBody(ByteArrayOutputStream.class); try { file.setContent(new String(output.toByteArray(), encoding)); } catch (UnsupportedEncodingException e) { LOG.error("Failed to convert file content to String. Invalid file encoding: {}", encoding); } file.setSize(output.size()); in.setBody(file); } @Override void customize(ComponentProxyComponent component, Map<String, Object> options); }### Answer: @Test public void testAfterProducer() throws Exception { String id = "12345"; String content = "Test content: åäö"; String encoding = StandardCharsets.ISO_8859_1.name(); int size = content.getBytes(encoding).length; Map<String, Object> options = new HashMap<>(); options.put("fileId", id); options.put("encoding", encoding); customizer.customize(component, options); Exchange inbound = new DefaultExchange(createCamelContext()); setBody(inbound, content, encoding); component.getAfterProducer().process(inbound); BoxFile file = inbound.getIn().getBody(BoxFile.class); assertNotNull(file); assertEquals(id, file.getId()); assertEquals(content, file.getContent()); assertEquals(size, file.getSize()); }
### Question: ServiceNowMetaDataExtension extends AbstractMetaDataExtension { @Override public Optional<MetaData> meta(Map<String, Object> parameters) { final String objectType = ConnectorOptions.extractOption(parameters, OBJECT_TYPE); final String metaType = ConnectorOptions.extractOption(parameters, META_TYPE, "definition"); if (ObjectHelper.equalIgnoreCase(objectType, ServiceNowConstants.RESOURCE_TABLE) && ObjectHelper.equalIgnoreCase(metaType, "definition")) { final MetaContext context = new MetaContext(parameters); ObjectHelper.notNull(context.getObjectType(), OBJECT_TYPE); ObjectHelper.notNull(context.getObjectName(), OBJECT_NAME); try { return tableDefinition(context); } catch (Exception e) { throw new IllegalStateException(e); } } if (ObjectHelper.equalIgnoreCase(objectType, ServiceNowConstants.RESOURCE_TABLE) && ObjectHelper.equalIgnoreCase(metaType, "list")) { final MetaContext context = new MetaContext(parameters); ObjectHelper.notNull(context.getObjectType(), OBJECT_TYPE); try { return tableList(context); } catch (Exception e) { throw new IllegalStateException(e); } } if (ObjectHelper.equalIgnoreCase(objectType, ServiceNowConstants.RESOURCE_IMPORT) && ObjectHelper.equalIgnoreCase(metaType, "list")) { final MetaContext context = new MetaContext(parameters); ObjectHelper.notNull(context.getObjectType(), OBJECT_TYPE); try { return importSetList(context); } catch (Exception e) { throw new IllegalStateException(e); } } throw new UnsupportedOperationException("Unsupported object type <" + objectType + ">"); } ServiceNowMetaDataExtension(CamelContext context); @Override Optional<MetaData> meta(Map<String, Object> parameters); static final String OBJECT_TYPE; static final String OBJECT_NAME; static final String META_TYPE; static final String TYPE; static final String ADDITIONAL_PROPERTIES; static final String ID; static final String SCHEMA; static final String TABLE; static final String SYS_DB_OBJECT; static final String NOW; static final String SYSPARM_EXCLUDE_REFERENCE_LINK; static final String SYSPARM_FIELDS; static final String SYSPARM_QUERY; }### Answer: @Test public void retrieveTableListTes() { CamelContext context = new DefaultCamelContext(); ServiceNowMetaDataExtension extension = new ServiceNowMetaDataExtension(context); Map<String, Object> properties = new HashMap<>(); properties.put("instanceName", System.getProperty("servicenow.instance")); properties.put("userName", System.getProperty("servicenow.username")); properties.put("password", System.getProperty("servicenow.password")); properties.put("objectType", ServiceNowConstants.RESOURCE_TABLE); properties.put("metaType", "list"); Optional<MetaDataExtension.MetaData> meta = extension.meta(properties); assertThat(meta).isPresent(); assertThat(meta.get().getPayload()).isInstanceOf(JsonNode.class); assertThat(meta.get().getAttributes()).hasEntrySatisfying(MetaDataExtension.MetaData.JAVA_TYPE, new Condition<Object>() { @Override public boolean matches(Object val) { return Objects.equals(JsonNode.class, val); } }); assertThat(meta.get().getAttributes()).hasEntrySatisfying(MetaDataExtension.MetaData.CONTENT_TYPE, new Condition<Object>() { @Override public boolean matches(Object val) { return Objects.equals("application/json", val); } }); assertThat(meta.get().getAttributes()).hasEntrySatisfying("Meta-Context", new Condition<Object>() { @Override public boolean matches(Object val) { return Objects.equals("import", val); } }); }
### Question: GoogleSheetsUpdateSpreadsheetCustomizer implements ComponentProxyCustomizer { private static void afterProducer(Exchange exchange) { final Message in = exchange.getIn(); final BatchUpdateSpreadsheetResponse batchUpdateResponse = in.getBody(BatchUpdateSpreadsheetResponse.class); GoogleSpreadsheet model = new GoogleSpreadsheet(); model.setSpreadsheetId(batchUpdateResponse.getSpreadsheetId()); if (ObjectHelper.isNotEmpty(batchUpdateResponse.getUpdatedSpreadsheet())) { SpreadsheetProperties spreadsheetProperties = batchUpdateResponse.getUpdatedSpreadsheet().getProperties(); if (ObjectHelper.isNotEmpty(spreadsheetProperties)) { model.setTitle(spreadsheetProperties.getTitle()); model.setUrl(batchUpdateResponse.getUpdatedSpreadsheet().getSpreadsheetUrl()); model.setTimeZone(spreadsheetProperties.getTimeZone()); model.setLocale(spreadsheetProperties.getLocale()); } List<GoogleSheet> sheets = new ArrayList<>(); if (ObjectHelper.isNotEmpty(batchUpdateResponse.getUpdatedSpreadsheet().getSheets())) { batchUpdateResponse.getUpdatedSpreadsheet().getSheets().stream() .map(Sheet::getProperties) .forEach(props -> { GoogleSheet sheet = new GoogleSheet(); sheet.setSheetId(props.getSheetId()); sheet.setIndex(props.getIndex()); sheet.setTitle(props.getTitle()); sheets.add(sheet); }); } model.setSheets(sheets); } in.setBody(model); } @Override void customize(ComponentProxyComponent component, Map<String, Object> options); }### Answer: @Test public void testAfterProducer() throws Exception { customizer.customize(getComponent(), new HashMap<>()); Exchange inbound = new DefaultExchange(createCamelContext()); BatchUpdateSpreadsheetResponse batchUpdateResponse = new BatchUpdateSpreadsheetResponse(); batchUpdateResponse.setSpreadsheetId(getSpreadsheetId()); Spreadsheet spreadsheet = new Spreadsheet(); spreadsheet.setSpreadsheetId(getSpreadsheetId()); SpreadsheetProperties spreadsheetProperties = new SpreadsheetProperties(); spreadsheetProperties.setTitle("SyndesisTest"); spreadsheetProperties.setTimeZone("America/New_York"); spreadsheetProperties.setLocale("en"); spreadsheet.setProperties(spreadsheetProperties); Sheet sheet = new Sheet(); SheetProperties sheetProperties = new SheetProperties(); sheetProperties.setTitle("Sheet1"); sheetProperties.setSheetId(1); sheetProperties.setIndex(1); sheet.setProperties(sheetProperties); spreadsheet.setSheets(Collections.singletonList(sheet)); batchUpdateResponse.setUpdatedSpreadsheet(spreadsheet); inbound.getIn().setBody(batchUpdateResponse); getComponent().getAfterProducer().process(inbound); GoogleSpreadsheet model = (GoogleSpreadsheet) inbound.getIn().getBody(); Assert.assertEquals(getSpreadsheetId(), model.getSpreadsheetId()); Assert.assertEquals("SyndesisTest", model.getTitle()); Assert.assertEquals("America/New_York", model.getTimeZone()); Assert.assertEquals("en", model.getLocale()); Assert.assertEquals(1, model.getSheets().size()); Assert.assertEquals("Sheet1", model.getSheets().get(0).getTitle()); Assert.assertEquals(Integer.valueOf(1), model.getSheets().get(0).getSheetId()); Assert.assertEquals(Integer.valueOf(1), model.getSheets().get(0).getIndex()); }
### Question: CellCoordinate { public static CellCoordinate fromCellId(String cellId) { CellCoordinate coordinate = new CellCoordinate(); if (cellId != null) { coordinate.setRowIndex(getRowIndex(cellId)); coordinate.setColumnIndex(getColumnIndex(cellId)); } return coordinate; } CellCoordinate(); static CellCoordinate fromCellId(String cellId); static String getColumnName(int columnIndex); static String getColumnName(int columnIndex, int columnStartIndex, String ... columnNames); int getRowIndex(); void setRowIndex(int rowIndex); int getColumnIndex(); void setColumnIndex(int columnIndex); }### Answer: @Test public void testFromCellId() { CellCoordinate coordinate = CellCoordinate.fromCellId(cellId); Assert.assertEquals(rowIndexCheck, coordinate.getRowIndex()); Assert.assertEquals(columnIndexCheck, coordinate.getColumnIndex()); }
### Question: CellCoordinate { public static String getColumnName(int columnIndex) { String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; StringBuilder columnName = new StringBuilder(); int index = columnIndex; int overflowIndex = -1; while (index > 25) { overflowIndex++; index -= 26; } if (overflowIndex >= 0) { columnName.append(alphabet.toCharArray()[overflowIndex]); } columnName.append(alphabet.toCharArray()[index]); return columnName.toString(); } CellCoordinate(); static CellCoordinate fromCellId(String cellId); static String getColumnName(int columnIndex); static String getColumnName(int columnIndex, int columnStartIndex, String ... columnNames); int getRowIndex(); void setRowIndex(int rowIndex); int getColumnIndex(); void setColumnIndex(int columnIndex); }### Answer: @Test public void testGetColumnName() { Assert.assertEquals(columnName, CellCoordinate.getColumnName(columnIndexCheck)); String[] names = new String[columnIndexCheck]; Arrays.fill(names, "Foo"); Assert.assertEquals(columnName, CellCoordinate.getColumnName(columnIndexCheck, 0, names)); names = new String[columnIndexCheck + 1]; Arrays.fill(names, "Foo"); Assert.assertEquals("Foo", CellCoordinate.getColumnName(columnIndexCheck, 0, names)); Assert.assertEquals("Foo", CellCoordinate.getColumnName(columnIndexCheck, columnIndexCheck, names)); }
### Question: RangeCoordinate extends CellCoordinate { public static RangeCoordinate fromRange(String range) { RangeCoordinate coordinate = new RangeCoordinate(); String rangeExpression = normalizeRange(range); if (rangeExpression.contains(":")) { String[] coordinates = rangeExpression.split(":", -1); coordinate.setRowStartIndex(getRowIndex(coordinates[0])); coordinate.setColumnStartIndex(getColumnIndex(coordinates[0])); coordinate.setRowEndIndex(getRowIndex(coordinates[1]) + 1); coordinate.setColumnEndIndex(getColumnIndex(coordinates[1]) + 1); } else { CellCoordinate cellCoordinate = CellCoordinate.fromCellId(rangeExpression); coordinate.setRowIndex(cellCoordinate.getRowIndex()); coordinate.setColumnIndex(cellCoordinate.getColumnIndex()); coordinate.setRowStartIndex(cellCoordinate.getRowIndex()); coordinate.setColumnStartIndex(cellCoordinate.getColumnIndex()); coordinate.setRowEndIndex(cellCoordinate.getRowIndex() + 1); coordinate.setColumnEndIndex(cellCoordinate.getColumnIndex() + 1); } return coordinate; } private RangeCoordinate(); static RangeCoordinate fromRange(String range); String getColumnNames(); int getRowStartIndex(); void setRowStartIndex(int rowStartIndex); int getRowEndIndex(); void setRowEndIndex(int rowEndIndex); int getColumnStartIndex(); void setColumnStartIndex(int columnStartIndex); int getColumnEndIndex(); void setColumnEndIndex(int columnEndIndex); static final String DIMENSION_ROWS; static final String DIMENSION_COLUMNS; }### Answer: @Test public void testFromRange() { RangeCoordinate coordinate = RangeCoordinate.fromRange(range); Assert.assertEquals(rowStartIndex, coordinate.getRowStartIndex()); Assert.assertEquals(rowEndIndex, coordinate.getRowEndIndex()); Assert.assertEquals(columnStartIndex, coordinate.getColumnStartIndex()); Assert.assertEquals(columnEndIndex, coordinate.getColumnEndIndex()); }
### Question: GoogleSheetsCreateSpreadsheetCustomizer implements ComponentProxyCustomizer { @Override public void customize(ComponentProxyComponent component, Map<String, Object> options) { setApiMethod(options); component.setBeforeProducer(this::beforeProducer); component.setAfterProducer(GoogleSheetsCreateSpreadsheetCustomizer::afterProducer); } @Override void customize(ComponentProxyComponent component, Map<String, Object> options); }### Answer: @Test public void testBeforeProducerFromOptions() throws Exception { Map<String, Object> options = new HashMap<>(); options.put("title", "SyndesisTest"); options.put("timeZone", "America/New_York"); options.put("locale", "en"); customizer.customize(getComponent(), options); Exchange inbound = new DefaultExchange(createCamelContext()); getComponent().getBeforeProducer().process(inbound); Assert.assertEquals(GoogleSheetsApiCollection.getCollection().getApiName(SheetsSpreadsheetsApiMethod.class).getName(), ConnectorOptions.extractOption(options, "apiName")); Assert.assertEquals("create", ConnectorOptions.extractOption(options, "methodName")); Spreadsheet spreadsheet = (Spreadsheet) inbound.getIn().getHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "content"); Assert.assertNull(spreadsheet.getSpreadsheetId()); Assert.assertEquals("SyndesisTest", spreadsheet.getProperties().getTitle()); Assert.assertEquals("America/New_York", spreadsheet.getProperties().getTimeZone()); Assert.assertEquals("en", spreadsheet.getProperties().getLocale()); Assert.assertNull(spreadsheet.getSheets()); } @Test public void testBeforeProducerFromModel() throws Exception { customizer.customize(getComponent(), new HashMap<>()); Exchange inbound = new DefaultExchange(createCamelContext()); GoogleSpreadsheet model = new GoogleSpreadsheet(); model.setTitle("SyndesisTest"); model.setTimeZone("America/New_York"); model.setLocale("en"); GoogleSheet sheetModel = new GoogleSheet(); sheetModel.setTitle("Sheet1"); sheetModel.setSheetId(1); sheetModel.setIndex(1); model.setSheets(Collections.singletonList(sheetModel)); inbound.getIn().setBody(model); getComponent().getBeforeProducer().process(inbound); Spreadsheet spreadsheet = (Spreadsheet) inbound.getIn().getHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "content"); Assert.assertNull(spreadsheet.getSpreadsheetId()); Assert.assertEquals("SyndesisTest", spreadsheet.getProperties().getTitle()); Assert.assertEquals("America/New_York", spreadsheet.getProperties().getTimeZone()); Assert.assertEquals("en", spreadsheet.getProperties().getLocale()); Assert.assertNotNull(spreadsheet.getSheets()); Assert.assertEquals(1, spreadsheet.getSheets().size()); Assert.assertEquals("Sheet1", spreadsheet.getSheets().get(0).getProperties().getTitle()); }
### Question: GoogleSheetsCreateSpreadsheetCustomizer implements ComponentProxyCustomizer { private static void afterProducer(Exchange exchange) { final Message in = exchange.getIn(); final Spreadsheet spreadsheet = in.getBody(Spreadsheet.class); GoogleSpreadsheet model = new GoogleSpreadsheet(); if (ObjectHelper.isNotEmpty(spreadsheet)) { model.setSpreadsheetId(spreadsheet.getSpreadsheetId()); SpreadsheetProperties spreadsheetProperties = spreadsheet.getProperties(); if (ObjectHelper.isNotEmpty(spreadsheetProperties)) { model.setTitle(spreadsheetProperties.getTitle()); model.setUrl(spreadsheet.getSpreadsheetUrl()); model.setTimeZone(spreadsheetProperties.getTimeZone()); model.setLocale(spreadsheetProperties.getLocale()); } List<GoogleSheet> sheets = new ArrayList<>(); if (ObjectHelper.isNotEmpty(spreadsheet.getSheets())) { spreadsheet.getSheets().stream() .map(Sheet::getProperties) .forEach(props -> { GoogleSheet sheet = new GoogleSheet(); sheet.setSheetId(props.getSheetId()); sheet.setIndex(props.getIndex()); sheet.setTitle(props.getTitle()); sheets.add(sheet); }); } model.setSheets(sheets); } in.setBody(model); } @Override void customize(ComponentProxyComponent component, Map<String, Object> options); }### Answer: @Test public void testAfterProducer() throws Exception { customizer.customize(getComponent(), new HashMap<>()); Exchange inbound = new DefaultExchange(createCamelContext()); Spreadsheet spreadsheet = new Spreadsheet(); spreadsheet.setSpreadsheetId(getSpreadsheetId()); SpreadsheetProperties spreadsheetProperties = new SpreadsheetProperties(); spreadsheetProperties.setTitle("SyndesisTest"); spreadsheetProperties.setTimeZone("America/New_York"); spreadsheetProperties.setLocale("en"); spreadsheet.setProperties(spreadsheetProperties); Sheet sheet = new Sheet(); SheetProperties sheetProperties = new SheetProperties(); sheetProperties.setTitle("Sheet1"); sheetProperties.setSheetId(1); sheetProperties.setIndex(1); sheet.setProperties(sheetProperties); spreadsheet.setSheets(Collections.singletonList(sheet)); inbound.getIn().setBody(spreadsheet); getComponent().getAfterProducer().process(inbound); GoogleSpreadsheet model = (GoogleSpreadsheet) inbound.getIn().getBody(); Assert.assertEquals(getSpreadsheetId(), model.getSpreadsheetId()); Assert.assertEquals("SyndesisTest", model.getTitle()); Assert.assertEquals("America/New_York", model.getTimeZone()); Assert.assertEquals("en", model.getLocale()); Assert.assertEquals(1, model.getSheets().size()); Assert.assertEquals("Sheet1", model.getSheets().get(0).getTitle()); Assert.assertEquals(Integer.valueOf(1), model.getSheets().get(0).getSheetId()); Assert.assertEquals(Integer.valueOf(1), model.getSheets().get(0).getIndex()); }
### Question: GoogleSheetsGetValuesCustomizer implements ComponentProxyCustomizer { private void beforeConsumer(Exchange exchange) throws JsonProcessingException { final Message in = exchange.getIn(); if (splitResults) { in.setBody(createModelFromSplitValues(in)); } else { in.setBody(createModelFromValueRange(in)); } } @Override void customize(ComponentProxyComponent component, Map<String, Object> options); static final String SPREADSHEET_ID; }### Answer: @Test public void testBeforeConsumer() throws Exception { Map<String, Object> options = new HashMap<>(); options.put("spreadsheetId", getSpreadsheetId()); options.put("range", range); options.put("splitResults", false); customizer.customize(getComponent(), options); Exchange inbound = new DefaultExchange(createCamelContext()); ValueRange valueRange = new ValueRange(); valueRange.setRange(sheetName + "!" + range); valueRange.setMajorDimension(majorDimension); valueRange.setValues(values); inbound.getIn().setBody(valueRange); getComponent().getBeforeConsumer().process(inbound); Assert.assertEquals(GoogleSheetsApiCollection.getCollection().getApiName(SheetsSpreadsheetsValuesApiMethod.class).getName(), ConnectorOptions.extractOption(options, "apiName")); Assert.assertEquals("get", ConnectorOptions.extractOption(options, "methodName")); @SuppressWarnings("unchecked") List<String> model = inbound.getIn().getBody(List.class); Assert.assertEquals(expectedValueModel.size(), model.size()); Iterator<String> modelIterator = model.iterator(); for (String expected : expectedValueModel) { assertThatJson(modelIterator.next()).isEqualTo(String.format(expected, getSpreadsheetId())); } }
### Question: GoogleSheetsGetSpreadsheetCustomizer implements ComponentProxyCustomizer { private static void beforeConsumer(Exchange exchange) { final Message in = exchange.getIn(); final Spreadsheet spreadsheet = exchange.getIn().getBody(Spreadsheet.class); GoogleSpreadsheet model = new GoogleSpreadsheet(); if (ObjectHelper.isNotEmpty(spreadsheet)) { model.setSpreadsheetId(spreadsheet.getSpreadsheetId()); SpreadsheetProperties spreadsheetProperties = spreadsheet.getProperties(); if (ObjectHelper.isNotEmpty(spreadsheetProperties)) { model.setTitle(spreadsheetProperties.getTitle()); model.setUrl(spreadsheet.getSpreadsheetUrl()); model.setTimeZone(spreadsheetProperties.getTimeZone()); model.setLocale(spreadsheetProperties.getLocale()); } List<GoogleSheet> sheets = new ArrayList<>(); if (ObjectHelper.isNotEmpty(spreadsheet.getSheets())) { spreadsheet.getSheets().stream() .map(Sheet::getProperties) .forEach(props -> { GoogleSheet sheet = new GoogleSheet(); sheet.setSheetId(props.getSheetId()); sheet.setIndex(props.getIndex()); sheet.setTitle(props.getTitle()); sheets.add(sheet); }); } model.setSheets(sheets); } in.setBody(model); } @Override void customize(ComponentProxyComponent component, Map<String, Object> options); }### Answer: @Test public void testBeforeConsumer() throws Exception { Map<String, Object> options = new HashMap<>(); options.put("spreadsheetId", getSpreadsheetId()); customizer.customize(getComponent(), options); Exchange inbound = new DefaultExchange(createCamelContext()); Spreadsheet spreadsheet = new Spreadsheet(); spreadsheet.setSpreadsheetId(getSpreadsheetId()); SpreadsheetProperties spreadsheetProperties = new SpreadsheetProperties(); spreadsheetProperties.setTitle("SyndesisTest"); spreadsheetProperties.setTimeZone("America/New_York"); spreadsheetProperties.setLocale("en"); spreadsheet.setProperties(spreadsheetProperties); Sheet sheet = new Sheet(); SheetProperties sheetProperties = new SheetProperties(); sheetProperties.setTitle("Sheet1"); sheetProperties.setSheetId(1); sheetProperties.setIndex(1); sheet.setProperties(sheetProperties); spreadsheet.setSheets(Collections.singletonList(sheet)); inbound.getIn().setBody(spreadsheet); getComponent().getBeforeConsumer().process(inbound); Assert.assertEquals(GoogleSheetsApiCollection.getCollection().getApiName(SheetsSpreadsheetsApiMethod.class).getName(), ConnectorOptions.extractOption(options, "apiName")); Assert.assertEquals("get", ConnectorOptions.extractOption(options, "methodName")); GoogleSpreadsheet model = (GoogleSpreadsheet) inbound.getIn().getBody(); Assert.assertEquals(getSpreadsheetId(), model.getSpreadsheetId()); Assert.assertEquals("SyndesisTest", model.getTitle()); Assert.assertEquals("America/New_York", model.getTimeZone()); Assert.assertEquals("en", model.getLocale()); Assert.assertEquals(1, model.getSheets().size()); Assert.assertEquals("Sheet1", model.getSheets().get(0).getTitle()); Assert.assertEquals(Integer.valueOf(1), model.getSheets().get(0).getSheetId()); Assert.assertEquals(Integer.valueOf(1), model.getSheets().get(0).getIndex()); }
### Question: SpecificationResourceCustomizer implements ComponentProxyCustomizer { @Override public void customize(final ComponentProxyComponent component, final Map<String, Object> options) { consumeOption(options, "specification", specificationObject -> { try { final String authenticationType = ConnectorOptions.extractOption(options, "authenticationType"); final String specification = updateSecuritySpecification((String) specificationObject, authenticationType); final File tempSpecification = File.createTempFile("rest-swagger", ".json"); tempSpecification.deleteOnExit(); final String swaggerSpecificationPath = tempSpecification.getAbsolutePath(); try (OutputStream out = new FileOutputStream(swaggerSpecificationPath)) { IOUtils.write(specification, out, StandardCharsets.UTF_8); } options.put("specificationUri", "file:" + swaggerSpecificationPath); } catch (final JsonProcessingException jsonException) { throw new IllegalStateException("Unable to parse openapi specification", jsonException); } catch (final IOException e) { throw new IllegalStateException("Unable to persist the specification to filesystem", e); } }); } @Override void customize(final ComponentProxyComponent component, final Map<String, Object> options); }### Answer: @Test public void shouldStoreSpecificationInTemporaryDirectory() { final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer(); final Map<String, Object> options = new HashMap<>(); options.put("specification", "the specification is here"); customizer.customize(NOT_USED, options); assertThat(options).containsKey("specificationUri"); assertThat(options).doesNotContainKey("specification"); assertThat(new File(StringHelper.after(ConnectorOptions.extractOption(options, "specificationUri"), "file:"))).hasContent("the specification is here"); } @Test public void shouldRemoveUnwantedSecurity() throws IOException { final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer(); final String spec = RestSwaggerConnectorIntegrationTest.readSpecification("apikey.json"); final String specUpdated = RestSwaggerConnectorIntegrationTest.readSpecification("apikey-security-updated.json"); final Map<String, Object> options = new HashMap<>(); options.put("specification", spec); options.put("authenticationType", "apiKey: api-key-header"); customizer.customize(NOT_USED, options); assertThat(options).containsKey("specificationUri"); assertThat(options).doesNotContainKey("specification"); assertThat(new File(StringHelper.after(ConnectorOptions.extractOption(options, "specificationUri"), "file:"))).hasContent(specUpdated); } @Test public void shouldNotUpdateSpecificationOnMissingSecurityDefinitionName() throws IOException { final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer(); final String spec = RestSwaggerConnectorIntegrationTest.readSpecification("apikey.json"); final Map<String, Object> options = new HashMap<>(); options.put("specification", spec); options.put("authenticationType", "apiKey"); customizer.customize(NOT_USED, options); assertThat(options).containsKey("specificationUri"); assertThat(options).doesNotContainKey("specification"); assertThat(new File(StringHelper.after(ConnectorOptions.extractOption(options, "specificationUri"), "file:"))).hasContent(spec); } @Test public void shouldNotUpdateSpecificationOnNullSecurityDefinitionName() throws IOException { final SpecificationResourceCustomizer customizer = new SpecificationResourceCustomizer(); final String spec = RestSwaggerConnectorIntegrationTest.readSpecification("apikey.json"); final Map<String, Object> options = new HashMap<>(); options.put("specification", spec); customizer.customize(NOT_USED, options); assertThat(options).containsKey("specificationUri"); assertThat(options).doesNotContainKey("specification"); assertThat(new File(StringHelper.after(ConnectorOptions.extractOption(options, "specificationUri"), "file:"))).hasContent(spec); }
### Question: SwaggerProxyComponent extends ComponentProxyComponent { public SwaggerProxyComponent(final String componentId, final String componentScheme) { super(componentId, componentScheme); } SwaggerProxyComponent(final String componentId, final String componentScheme); @Override Endpoint createEndpoint(final String uri); void overrideEndpoint(final Function<Endpoint, Endpoint> endpointOverride); }### Answer: @Test public void testSwaggerProxyComponent() throws Exception { CamelContext context = new DefaultCamelContext(); ComponentProxyFactory factory = new ConnectorFactory(); ComponentProxyComponent proxy = factory.newInstance("swagger-1", "rest-openapi"); try { proxy.setCamelContext(context); proxy.start(); Endpoint endpoint = proxy.createEndpoint("swagger-1:http: assertThat(endpoint).isInstanceOfSatisfying(DelegateEndpoint.class, e -> { assertThat(e.getEndpoint()).isInstanceOf(RestOpenApiEndpoint.class); assertThat(e.getEndpoint()).hasFieldOrPropertyWithValue("componentName", SyndesisRestSwaggerComponent.COMPONENT_NAME); }); } finally { proxy.stop(); } }
### Question: ResponseCustomizer implements ComponentProxyCustomizer, OutputDataShapeAware { static boolean isUnifiedDataShape(final DataShape dataShape) { if (dataShape == null || dataShape.getKind() != DataShapeKinds.JSON_SCHEMA) { return false; } final String specification = dataShape.getSpecification(); if (ObjectHelper.isEmpty(specification)) { return false; } final JsonNode jsonSchema; try { jsonSchema = PayloadConverterBase.MAPPER.readTree(specification); } catch (final IOException e) { LOG.warn("Unable to parse data shape as a JSON: {}", e.getMessage()); LOG.debug("Failed parsing JSON datashape: `{}`", specification, e); return false; } final JsonNode id = jsonSchema.get("$id"); return !isNullNode(id) && "io:syndesis:wrapped".equals(id.asText()); } @Override void customize(final ComponentProxyComponent component, final Map<String, Object> options); @Override DataShape getOutputDataShape(); @Override void setOutputDataShape(final DataShape dataShape); }### Answer: @Test public void shouldDetermineAddingResponseConverterRobustly() { assertThat(ResponseCustomizer.isUnifiedDataShape(null)).isFalse(); assertThat(ResponseCustomizer.isUnifiedDataShape(new DataShape.Builder().build())).isFalse(); assertThat(ResponseCustomizer.isUnifiedDataShape(new DataShape.Builder().kind(DataShapeKinds.JAVA).build())).isFalse(); assertThat(ResponseCustomizer.isUnifiedDataShape(new DataShape.Builder().kind(DataShapeKinds.JSON_SCHEMA).build())).isFalse(); assertThat(ResponseCustomizer.isUnifiedDataShape(new DataShape.Builder().kind(DataShapeKinds.JSON_SCHEMA).specification("xyz").build())).isFalse(); assertThat(ResponseCustomizer.isUnifiedDataShape(new DataShape.Builder().kind(DataShapeKinds.JSON_SCHEMA).specification("{}").build())).isFalse(); } @Test public void shouldDetermineAddingResponseConverterWithWrappedSchema() { assertThat(ResponseCustomizer .isUnifiedDataShape(new DataShape.Builder().kind(DataShapeKinds.JSON_SCHEMA).specification("{\"$id\":\"io:syndesis:wrapped\"}").build())).isTrue(); }
### Question: SetHttpHeader extends SetHeader { @Override public void process(final Exchange exchange) throws Exception { super.process(exchange); SyndesisHeaderStrategy.whitelist(exchange, headerName); } SetHttpHeader(final String headerName, final String headerValue); @Override void process(final Exchange exchange); }### Answer: @Test public void shouldSetHeaderAndWhitelist() throws Exception { final Exchange exchange = new DefaultExchange(new DefaultCamelContext()); new SetHttpHeader("name", "value").process(exchange); assertThat(exchange.getIn().getHeader("name")).isEqualTo("value"); assertThat(SyndesisHeaderStrategy.isWhitelisted(exchange, "name")).isTrue(); }
### Question: LogStepHandler implements IntegrationStepHandler { @Override public Optional<ProcessorDefinition<?>> handle(Step step, ProcessorDefinition<?> route, IntegrationRouteBuilder builder, String flowIndex, String stepIndex) { final String message = createMessage(step); if (message.isEmpty()) { return Optional.empty(); } if (step.getId().isPresent()) { String stepId = step.getId().get(); return Optional.of(route.log(LoggingLevel.INFO, (String) null, stepId, message)); } return Optional.of(route.log(LoggingLevel.INFO, message)); } @Override boolean canHandle(Step step); @Override Optional<ProcessorDefinition<?>> handle(Step step, ProcessorDefinition<?> route, IntegrationRouteBuilder builder, String flowIndex, String stepIndex); }### Answer: @Test public void shouldAddLogProcessorWithCustomMessage() { final Step step = new Step.Builder().putConfiguredProperty("customText", "Log me baby one more time").build(); assertThat(handler.handle(step, route, NOT_USED, "1", "2")).contains(route); verify(route).log(LoggingLevel.INFO, "Log me baby one more time"); } @Test public void shouldAddLogProcessorWithCustomMessageAndStepId() { final Step step = new Step.Builder().id("step-id") .putConfiguredProperty("customText", "Log me baby one more time").build(); assertThat(handler.handle(step, route, NOT_USED, "1", "2")).contains(route); verify(route).log(LoggingLevel.INFO, (String) null, "step-id", "Log me baby one more time"); } @Test public void shouldNotAddLogProcessorWhenNotingIsSpecifiedToLog() { final Step step = new Step.Builder().build(); assertThat(handler.handle(step, route, NOT_USED, "1", "2")).isEmpty(); verifyZeroInteractions(route); }
### Question: AWSSNSMetaDataExtension extends AbstractMetaDataExtension { @Override public Optional<MetaData> meta(Map<String, Object> parameters) { final String accessKey = ConnectorOptions.extractOption(parameters, "accessKey"); final String secretKey = ConnectorOptions.extractOption(parameters, "secretKey"); final String region = ConnectorOptions.extractOption(parameters, "region"); AmazonSNSClientBuilder clientBuilder; AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey); AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); clientBuilder = AmazonSNSClientBuilder.standard().withCredentials(credentialsProvider); clientBuilder = clientBuilder.withRegion(Regions.valueOf(region)); AmazonSNS sqsClient = clientBuilder.build(); try { ListTopicsResult result = sqsClient.listTopics(); Set<String> setTopic = new HashSet<String>(); if (result.getTopics() != null) { for (Topic entry : result.getTopics()) { setTopic.add(entry.getTopicArn()); } } return Optional.of(MetaDataBuilder.on(getCamelContext()).withAttribute(MetaData.CONTENT_TYPE, "text/plain").withAttribute(MetaData.JAVA_TYPE, String.class) .withPayload(setTopic).build()); } catch (Exception e) { throw new IllegalStateException("Get information about existing topics with has failed.", e); } } AWSSNSMetaDataExtension(CamelContext context); @Override Optional<MetaData> meta(Map<String, Object> parameters); }### Answer: @Test public void retrieveQueuesListTest() { CamelContext context = new DefaultCamelContext(); AWSSNSMetaDataExtension extension = new AWSSNSMetaDataExtension(context); Map<String, Object> properties = new HashMap<>(); properties.put("accessKey", "accessKey"); properties.put("secretKey", "secretKey"); properties.put("region", "region"); Optional<MetaDataExtension.MetaData> meta = extension.meta(properties); assertThat(meta).isPresent(); assertThat(meta.get().getPayload()).isInstanceOf(HashSet.class); assertThat(meta.get().getAttributes()).hasEntrySatisfying(MetaDataExtension.MetaData.JAVA_TYPE, new Condition<Object>() { @Override public boolean matches(Object val) { return Objects.equals(String.class, val); } }); assertThat(meta.get().getAttributes()).hasEntrySatisfying(MetaDataExtension.MetaData.CONTENT_TYPE, new Condition<Object>() { @Override public boolean matches(Object val) { return Objects.equals("text/plain", val); } }); } @Test public void noChannelTest() { CamelContext context = new DefaultCamelContext(); AWSSNSMetaDataExtension extension = new AWSSNSMetaDataExtension(context); Map<String, Object> properties = new HashMap<>(); properties.put("webhookurl", "token"); Optional<MetaDataExtension.MetaData> meta = extension.meta(properties); assertThat(meta).isEmpty(); }
### Question: GenerateConnectorInspectionsMojo extends AbstractMojo { public JsonNode validateWithSchema(File jsonFile) throws MojoExecutionException { InputStream jsonStream = null; try { jsonStream = new FileInputStream(jsonFile); JsonNode jsonNode = JsonUtils.reader().readTree(jsonStream); ProcessingReport report = jsonSchema.validate(jsonNode, true); if (! report.isSuccess()) { for (final ProcessingMessage processingMessage : report) { getLog().warn(processingMessage.toString()); } throw new MojoExecutionException("Validation of json file " + jsonFile.getName() + " failed, see previous logs"); } return jsonNode; } catch (IOException | ProcessingException ex) { throw new MojoExecutionException("Failure to validate json file " + jsonFile.getName(), ex); } finally { if (jsonStream != null) { try { jsonStream.close(); } catch (IOException e) { getLog().error(e); } } } } GenerateConnectorInspectionsMojo(); @Override void execute(); JsonNode validateWithSchema(File jsonFile); static DataShape generateInspections(URL[] classpath, DataShape shape); static JavaClass inspect(URL[] classpath, DataShape shape); }### Answer: @Test public void validFileAgainstSchema() throws Exception { GenerateConnectorInspectionsMojo mojo = new GenerateConnectorInspectionsMojo(); JsonNode jsonNode = mojo.validateWithSchema(getFile("/my-test-connector.json")); assertNotNull(jsonNode); } @Test public void unformedFileAgainstSchema() throws Exception { GenerateConnectorInspectionsMojo mojo = new GenerateConnectorInspectionsMojo(); String unformedConnectorFile = "my-unformed-connector.json"; assertThatExceptionOfType(MojoExecutionException.class) .isThrownBy(() -> { mojo.validateWithSchema(getFile("/" + unformedConnectorFile)); }) .withCauseInstanceOf(JsonParseException.class) .withStackTraceContaining("line: 9, column: 12"); } @Test public void invalidFileAgainstSchema() throws Exception { GenerateConnectorInspectionsMojo mojo = new GenerateConnectorInspectionsMojo(); String invalidConnectorFile = "my-invalid-connector.json"; assertThatExceptionOfType(MojoExecutionException.class) .isThrownBy(() -> { mojo.validateWithSchema(getFile("/" + invalidConnectorFile)); }) .withMessageContaining("Validation of json file " + invalidConnectorFile + " failed, see previous logs"); }
### Question: KeyStoreHelper { public KeyStoreHelper store() { try { KeyStore keyStore = CertificateUtil.createKeyStore(certificate, alias); tempFile = Files.createTempFile(alias, ".ks", PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------"))); password = generatePassword(); try (OutputStream stream = new FileOutputStream(tempFile.toFile())) { keyStore.store(stream, password.toCharArray()); } } catch (GeneralSecurityException | IOException e) { throw new IllegalArgumentException(String.format("Error creating key store %s: %s", alias, e.getMessage()), e); } return this; } KeyStoreHelper(String certificate, String alias); String getKeyStorePath(); String getPassword(); KeyStoreHelper store(); boolean clean(); static KeyStore defaultKeyStore(); static KeyStore createKeyStoreWithCustomCertificate(String alias, String certContent); }### Answer: @Test public void testStore() throws Exception { final KeyStoreHelper helper = new KeyStoreHelper(CertificateUtilTest.TEST_CERT, "test-cert"); helper.store(); assertThat(helper.getKeyStorePath()).isNotEmpty(); assertThat(helper.getPassword()).isNotEmpty(); }
### Question: ConnectorOptions { public static String extractOption(Map<String, ?> options, String key, String defaultValue) { if (options == null) { return defaultValue; } return Optional.ofNullable(options.get(key)) .map(Object::toString) .filter(v -> v.length() > 0) .orElse(defaultValue); } private ConnectorOptions(); static String extractOption(Map<String, ?> options, String key, String defaultValue); static String extractOption(Map<String, ?> options, String key); static String popOption(Map<String, ?> options, String key); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn, T defaultValue); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn); static void extractOptionAndConsume(Map<String, ?> options, String key, Consumer<String> consumer); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass, T defaultValue); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass); }### Answer: @Test public void testStringValue() { put(key, value); assertEquals(value, ConnectorOptions.extractOption(parameters, key)); assertNull(ConnectorOptions.extractOption(parameters, missingKey)); } @Test public void testStringValueWithDefault() { String defaultValue = "defaultValue"; put(key, value); assertEquals(value, ConnectorOptions.extractOption(parameters, key, defaultValue)); assertEquals(defaultValue, ConnectorOptions.extractOption(parameters, missingKey, defaultValue)); }
### Question: ConnectorOptions { public static <T> T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn, T defaultValue) { if (options == null) { return defaultValue; } try { return Optional.ofNullable(options.get(key)) .map(Object::toString) .filter(v -> v.length() > 0) .map(mappingFn) .orElse(defaultValue); } catch (Exception ex) { LOG.error("Evaluation of option '" + key + "' failed. Returning default value.", ex); return defaultValue; } } private ConnectorOptions(); static String extractOption(Map<String, ?> options, String key, String defaultValue); static String extractOption(Map<String, ?> options, String key); static String popOption(Map<String, ?> options, String key); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn, T defaultValue); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn); static void extractOptionAndConsume(Map<String, ?> options, String key, Consumer<String> consumer); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass, T defaultValue); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass); }### Answer: @Test public void testStringValueAndMap() throws Exception { put(key, value); assertEquals((Long) 1L, ConnectorOptions.extractOptionAndMap(parameters, key, this::convertLong)); assertNull(ConnectorOptions.extractOptionAndMap(parameters, missingKey, this::convertLong)); } @Test public void testStringValueAndMapWithDefault() { Long defaultValue = 2L; put(key, value); assertEquals((Long) 1L, ConnectorOptions.extractOptionAndMap(parameters, key, this::convertLong, defaultValue)); assertEquals(defaultValue, ConnectorOptions.extractOptionAndMap(parameters, missingKey, this::convertLong, defaultValue)); } @Test public void testStringValueAndMapToBooleanWithDefault() { put(key, Boolean.toString(true)); assertEquals(Boolean.TRUE, ConnectorOptions.extractOptionAndMap(parameters, key, Boolean::valueOf, false)); assertEquals(Boolean.FALSE, ConnectorOptions.extractOptionAndMap(parameters, missingKey, Boolean::valueOf, false)); put(key, "NotABoolean"); assertEquals(Boolean.FALSE, ConnectorOptions.extractOptionAndMap(parameters, key, Boolean::valueOf, false)); } @Test public void testStringValueAndMapToIntWithDefault() throws Exception { put(key, 2); assertTrue(2 == ConnectorOptions.extractOptionAndMap(parameters, key, Integer::parseInt, 3)); assertTrue(3 == ConnectorOptions.extractOptionAndMap(parameters, missingKey, Integer::parseInt, 3)); put(key, "NotAnInt"); assertTrue(-1 == ConnectorOptions.extractOptionAndMap(parameters, key, Integer::parseInt, -1)); }
### Question: ConnectorOptions { public static void extractOptionAndConsume(Map<String, ?> options, String key, Consumer<String> consumer) { if (options == null) { return; } try { Optional.ofNullable(options.get(key)) .map(Object::toString) .ifPresent(consumer); } catch (Exception ex) { LOG.error("Evaluation of option '" + key + "' failed.", ex); } } private ConnectorOptions(); static String extractOption(Map<String, ?> options, String key, String defaultValue); static String extractOption(Map<String, ?> options, String key); static String popOption(Map<String, ?> options, String key); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn, T defaultValue); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn); static void extractOptionAndConsume(Map<String, ?> options, String key, Consumer<String> consumer); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass, T defaultValue); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass); }### Answer: @Test public void testValueAndConsumer() { put(key, value); final int[] cRun = new int[1]; final int[] success = new int[1]; Consumer<String> c = (String v) -> { cRun[0] = 1; if (v.equals(value)) { success[0] = 1; } }; cRun[0] = 0; success[0] = 0; ConnectorOptions.extractOptionAndConsume(parameters, key, c); assertEquals(1, cRun[0]); assertEquals(1, success[0]); cRun[0] = 0; success[0] = 0; ConnectorOptions.extractOptionAndConsume(parameters, missingKey, c); assertEquals(0, cRun[0]); assertEquals(0, success[0]); }
### Question: ConnectorOptions { public static <T> T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass, T defaultValue) { if (options == null) { return defaultValue; } return Optional.ofNullable(options.get(key)) .filter(requiredClass::isInstance) .map(requiredClass::cast) .orElse(defaultValue); } private ConnectorOptions(); static String extractOption(Map<String, ?> options, String key, String defaultValue); static String extractOption(Map<String, ?> options, String key); static String popOption(Map<String, ?> options, String key); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn, T defaultValue); static T extractOptionAndMap(Map<String, ?> options, String key, Function<? super String, T> mappingFn); static void extractOptionAndConsume(Map<String, ?> options, String key, Consumer<String> consumer); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass, T defaultValue); static T extractOptionAsType(Map<String, ?> options, String key, Class<T> requiredClass); }### Answer: @Test public void testTypedValue() { Colours redValue = Colours.RED; put(key, redValue); assertEquals(redValue, ConnectorOptions.extractOptionAsType(parameters, key, Colours.class)); assertNull(ConnectorOptions.extractOptionAsType(parameters, missingKey, Colours.class)); }
### Question: CertificateUtil { public static KeyManager[] createKeyManagers(String clientCertificate, String alias) throws GeneralSecurityException, IOException { final KeyStore clientKs = createKeyStore(clientCertificate, alias); KeyManagerFactory kmFactory = KeyManagerFactory.getInstance("PKIX"); kmFactory.init(clientKs, null); return kmFactory.getKeyManagers(); } private CertificateUtil(); static KeyManager[] createKeyManagers(String clientCertificate, String alias); static TrustManager[] createTrustAllTrustManagers(); static TrustManager[] createTrustManagers(String brokerCertificate, String alias); static KeyStore createKeyStore(String certificate, String alias); static String getMultilineCertificate(String certificate); }### Answer: @Test public void testCreateKeyManagers() throws Exception { final KeyManager[] keyManagers = CertificateUtil.createKeyManagers(TEST_CERT, "test-cert"); assertThat(keyManagers).isNotNull().isNotEmpty(); }
### Question: LogStepHandler implements IntegrationStepHandler { static String createMessage(Step l) { StringBuilder sb = new StringBuilder(128); String customText = getCustomText(l.getConfiguredProperties()); boolean isContextLoggingEnabled = isContextLoggingEnabled(l.getConfiguredProperties()); boolean isBodyLoggingEnabled = isBodyLoggingEnabled(l.getConfiguredProperties()); if (isContextLoggingEnabled) { sb.append("Message Context: [${in.headers}] "); } if (isBodyLoggingEnabled) { sb.append("Body: [${bean:bodyLogger}] "); } if (customText != null && !customText.isEmpty() && !customText.equals("null")) { sb.append(customText); } return sb.toString(); } @Override boolean canHandle(Step step); @Override Optional<ProcessorDefinition<?>> handle(Step step, ProcessorDefinition<?> route, IntegrationRouteBuilder builder, String flowIndex, String stepIndex); }### Answer: @Test public void shouldGenerateMessages() { final Step step = new Step.Builder().putConfiguredProperty("customText", "Log me baby one more time").build(); assertThat(LogStepHandler.createMessage(step)).isEqualTo("Log me baby one more time"); final Step withContext = new Step.Builder().createFrom(step) .putConfiguredProperty("contextLoggingEnabled", "true").build(); assertThat(LogStepHandler.createMessage(withContext)) .isEqualTo("Message Context: [${in.headers}] Log me baby one more time"); final Step withBody = new Step.Builder().createFrom(step).putConfiguredProperty("bodyLoggingEnabled", "true") .build(); assertThat(LogStepHandler.createMessage(withBody)).isEqualTo("Body: [${bean:bodyLogger}] Log me baby one more time"); final Step withContextAndBody = new Step.Builder().createFrom(step) .putConfiguredProperty("contextLoggingEnabled", "true").putConfiguredProperty("bodyLoggingEnabled", "true") .build(); assertThat(LogStepHandler.createMessage(withContextAndBody)) .isEqualTo("Message Context: [${in.headers}] Body: [${bean:bodyLogger}] Log me baby one more time"); }
### Question: CertificateUtil { public static TrustManager[] createTrustManagers(String brokerCertificate, String alias) throws GeneralSecurityException, IOException { TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("X509"); trustManagerFactory.init(createKeyStore(brokerCertificate, alias)); return trustManagerFactory.getTrustManagers(); } private CertificateUtil(); static KeyManager[] createKeyManagers(String clientCertificate, String alias); static TrustManager[] createTrustAllTrustManagers(); static TrustManager[] createTrustManagers(String brokerCertificate, String alias); static KeyStore createKeyStore(String certificate, String alias); static String getMultilineCertificate(String certificate); }### Answer: @Test public void testCreateTrustManagers() throws Exception { final TrustManager[] trustManagers = CertificateUtil.createTrustManagers(TEST_CERT, "test-cert"); assertThat(trustManagers).isNotNull().isNotEmpty(); }
### Question: HttpRequestUnwrapperProcessor implements Processor { @Override public void process(final Exchange exchange) throws Exception { final Message message = exchange.getIn(); final Object body = message.getBody(); final JsonNode data = parseBody(body); if (data == null) { return; } final JsonNode paramMap = data.get("parameters"); final JsonNode bodyData = data.get("body"); if (paramMap != null || bodyData != null) { if (paramMap != null) { for (final String key : parameters) { final JsonNode valueNode = paramMap.get(key); if (valueNode != null) { final String val = valueNode.asText(); message.setHeader(key, val); } } } if (bodyData == null) { message.setBody(null); return; } if (bodyData.isContainerNode()) { message.setBody(JsonUtils.toString(bodyData)); return; } message.setHeader(Exchange.CONTENT_TYPE, "text/plain"); message.setBody(bodyData.asText()); } } HttpRequestUnwrapperProcessor(final JsonNode schema); @Override void process(final Exchange exchange); }### Answer: @Test public void shouldUnwrapArrayResponses() throws Exception { final Message in = new DefaultMessage(camelContext); exchange.setIn(in); in.setBody("{\"body\":[{\"b1\":\"c1\"},{\"b2\":\"c2\"}]}"); processor.process(exchange); assertThat(in.getBody()).isEqualTo("[{\"b1\":\"c1\"},{\"b2\":\"c2\"}]"); } @Test public void shouldUnwrapResponses() throws Exception { final Message in = new DefaultMessage(camelContext); exchange.setIn(in); in.setBody("{\"parameters\":{\"h1\":\"v1\",\"h3\":\"v3\"},\"body\":{\"b1\":\"c1\",\"b2\":\"c2\"}}"); processor.process(exchange); assertThat(in.getHeaders()).containsOnly(entry("h1", "v1"), entry("h3", "v3")); assertThat(in.getBody()).isEqualTo("{\"b1\":\"c1\",\"b2\":\"c2\"}"); } @Test public void simpleNonStringValuesShouldBeUnwrappedVerbatim() throws Exception { final Message in = new DefaultMessage(camelContext); exchange.setIn(in); in.setBody("{\"body\":123}"); processor.process(exchange); assertThat(in.getHeaders()).containsOnly(entry(Exchange.CONTENT_TYPE, "text/plain")); assertThat(in.getBody()).isEqualTo("123"); } @Test public void simpleValuesShouldBeUnwrappedVerbatim() throws Exception { final Message in = new DefaultMessage(camelContext); exchange.setIn(in); in.setBody("{\"body\":\"simple\"}"); processor.process(exchange); assertThat(in.getHeaders()).containsOnly(entry(Exchange.CONTENT_TYPE, "text/plain")); assertThat(in.getBody()).isEqualTo("simple"); }
### Question: ErrorMapper { public static Map<String, Integer> jsonToMap(String property) { try { if (ObjectHelper.isEmpty(property)) { return Collections.emptyMap(); } return JsonUtils.reader().forType(STRING_MAP_TYPE).readValue(property); } catch (IOException e) { LOG.warn(String.format("Failed to read error code mapping property %s: %s", property, e.getMessage()), e); return Collections.emptyMap(); } } private ErrorMapper(); static Map<String, Integer> jsonToMap(String property); static ErrorStatusInfo mapError(final Exception exception, final Map<String, Integer> httpResponseCodeMappings, final Integer defaultResponseCode); }### Answer: @Test public void testJsonToMap() { assertThat(errorResponseCodeMappings.size()).isEqualTo(4); assertThat(errorResponseCodeMappings.containsKey("SQL_CONNECTOR_ERROR")).isTrue(); }
### Question: ErrorMapper { public static ErrorStatusInfo mapError(final Exception exception, final Map<String, Integer> httpResponseCodeMappings, final Integer defaultResponseCode) { SyndesisConnectorException sce; if (isOrCausedBySyndesisConnectorException(exception)) { sce = extract(exception); } else { sce = fromRuntimeException(exception, httpResponseCodeMappings.keySet()); } if (sce == null) { sce = SyndesisConnectorException.from(exception); } Integer responseCode = httpResponseCodeMappings.get(sce.getCategory()) != null ? httpResponseCodeMappings.get(sce.getCategory()): defaultResponseCode; return new ErrorStatusInfo(responseCode, sce.getCategory(), Optional.ofNullable(sce.getMessage()).orElse("no message"), deriveErrorName(sce)); } private ErrorMapper(); static Map<String, Integer> jsonToMap(String property); static ErrorStatusInfo mapError(final Exception exception, final Map<String, Integer> httpResponseCodeMappings, final Integer defaultResponseCode); }### Answer: @Test public void testEmptyMap() { SyndesisConnectorException sce = new SyndesisConnectorException("SQL_CONNECTOR_ERROR", "error msg test"); ErrorStatusInfo info = ErrorMapper.mapError(sce, Collections.emptyMap(), 200); assertThat(info.getHttpResponseCode()).isEqualTo(200); assertThat(info.getCategory()).isEqualTo("SQL_CONNECTOR_ERROR"); assertThat(info.getMessage()).isEqualTo("error msg test"); } @Test public void testSyndesisEntityNotFOund() { Exception e = new SyndesisConnectorException("SQL_ENTITY_NOT_FOUND_ERROR", "entity not found"); ErrorStatusInfo info = ErrorMapper.mapError(e, errorResponseCodeMappings, 200); assertThat(info.getHttpResponseCode()).isEqualTo(404); assertThat(info.getCategory()).isEqualTo("SQL_ENTITY_NOT_FOUND_ERROR"); assertThat(info.getMessage()).isEqualTo("entity not found"); } @Test public void testUnmappedException() { Exception e = new Exception("Unmapped Exception"); ErrorStatusInfo info = ErrorMapper.mapError(e, errorResponseCodeMappings, 200); assertThat(info.getHttpResponseCode()).isEqualTo(500); assertThat(info.getCategory()).isEqualTo(ErrorCategory.SERVER_ERROR); assertThat(info.getMessage()).isEqualTo("Unmapped Exception"); } @Test public void testFileAlreadyExistsException() { Exception e = new FileAlreadyExistsException("myfile"); ErrorStatusInfo info = ErrorMapper.mapError(e, errorResponseCodeMappings, 200); assertThat(info.getHttpResponseCode()).isEqualTo(500); assertThat(info.getCategory()).isEqualTo("SERVER_ERROR"); assertThat(info.getMessage()).isEqualTo("myfile"); assertThat(info.getError()).isEqualTo("file_already_exists_error"); }
### Question: ExcludeFilter implements ArtifactsFilter { @Override public Set<Artifact> filter(final Set<Artifact> artifacts) throws ArtifactFilterException { final Set<Artifact> included = new HashSet<>(); for (final Artifact given : artifacts) { if (isArtifactIncluded(given)) { included.add(given); } } return included; } ExcludeFilter(final String excludedGroupId, final String excludedArtifactId); @Override Set<Artifact> filter(final Set<Artifact> artifacts); @Override boolean isArtifactIncluded(final Artifact artifact); }### Answer: @Test public void shouldPerformFiltering() throws ArtifactFilterException { final Set<Artifact> given = new HashSet<>(); given.add(included1); given.add(excluded); given.add(included2); assertThat(filter.filter(given)).containsOnly(included1, included2); }
### Question: PrometheusMetricsProviderImpl implements MetricsProvider { @Override public IntegrationMetricsSummary getIntegrationMetricsSummary(String integrationId) { final Map<String, Long> totalMessagesMap = getMetricValues(integrationId, METRIC_TOTAL, deploymentVersionLabel, Long.class, PrometheusMetricsProviderImpl::sum); final Map<String, Long> failedMessagesMap = getMetricValues(integrationId, METRIC_FAILED, deploymentVersionLabel, Long.class, PrometheusMetricsProviderImpl::sum); final Map<String, Instant> startTimeMap = getMetricValues(integrationId, METRIC_START_TIMESTAMP, deploymentVersionLabel, Instant.class, PrometheusMetricsProviderImpl::max); final Map<String, Instant> lastCompletedTimeMap = getMetricValues(integrationId, METRIC_COMPLETED_TIMESTAMP, deploymentVersionLabel, Instant.class, PrometheusMetricsProviderImpl::max); final Map<String, Instant> lastFailedTimeMap = getMetricValues(integrationId, METRIC_FAILURE_TIMESTAMP, deploymentVersionLabel, Instant.class, PrometheusMetricsProviderImpl::max); final Map<String, Instant> lastProcessedTimeMap = Stream.concat(lastCompletedTimeMap.entrySet().stream(), lastFailedTimeMap.entrySet().stream()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, PrometheusMetricsProviderImpl::max)); final Optional<Instant> startTime = getAggregateMetricValue(integrationId, METRIC_START_TIMESTAMP, Instant.class, MIN); final Optional<Instant> lastCompletedTime = getAggregateMetricValue(integrationId, METRIC_COMPLETED_TIMESTAMP, Instant.class, MAX); final Optional<Instant> lastFailureTime = getAggregateMetricValue(integrationId, METRIC_FAILURE_TIMESTAMP, Instant.class, MAX); final Instant lastProcessedTime = max(lastCompletedTime.orElse(null), lastFailureTime.orElse(null)); return createIntegrationMetricsSummary(totalMessagesMap, failedMessagesMap, startTimeMap, lastProcessedTimeMap, startTime, Optional.ofNullable(lastProcessedTime)); } protected PrometheusMetricsProviderImpl(PrometheusConfigurationProperties config, NamespacedOpenShiftClient openShiftClient); @PostConstruct void init(); @PreDestroy void destroy(); @Override IntegrationMetricsSummary getIntegrationMetricsSummary(String integrationId); @Override IntegrationMetricsSummary getTotalIntegrationMetricsSummary(); static final String OPERATOR_TOPK; static final String MIN; static final String MAX; }### Answer: @Test public void testGetIntegrationMetricsSummary() throws Exception { final IntegrationMetricsSummary summary = metricsProvider.getIntegrationMetricsSummary(TEST_INTEGRATION_ID); assertThat(summary.getMessages()).isNotNull(); final Optional<List<IntegrationDeploymentMetrics>> deploymentMetrics = summary .getIntegrationDeploymentMetrics(); assertThat(deploymentMetrics).isNotEmpty().map(List::isEmpty).hasValue(false); }
### Question: PrometheusMetricsProviderImpl implements MetricsProvider { @Override public IntegrationMetricsSummary getTotalIntegrationMetricsSummary() { final Optional<Long> totalMessages = getSummaryMetricValue(METRIC_TOTAL, Long.class, "sum"); final Optional<Long> failedMessages = getSummaryMetricValue(METRIC_FAILED, Long.class, "sum"); final List<Pod> serverList = openShiftClient.pods().withLabelSelector(SELECTOR).list().getItems(); final Optional<Instant> startTime; if (!serverList.isEmpty()) { startTime = Optional.of(Instant.parse(serverList.get(0).getStatus().getStartTime())); } else { if (LOG.isWarnEnabled()) { LOG.warn("Missing syndesis-server pod in lookup with selector " + LABELS); } startTime = Optional.empty(); } final Optional<Instant> lastCompletedTime = getAggregateMetricValue(METRIC_COMPLETED_TIMESTAMP, Instant.class, MAX); final Optional<Instant> lastFailureTime = getAggregateMetricValue(METRIC_FAILURE_TIMESTAMP, Instant.class, MAX); final Optional<Instant> lastProcessedTime = Optional.ofNullable(max(lastCompletedTime.orElse(null), lastFailureTime.orElse(null))); return new IntegrationMetricsSummary.Builder() .metricsProvider("prometheus") .start(startTime.map(st -> Instant.ofEpochMilli(st.toEpochMilli() * 1000))) .lastProcessed(lastProcessedTime.map(lp -> Instant.ofEpochMilli(lp.toEpochMilli() * 1000))) .uptimeDuration(startTime.map(date -> Duration.between(date, Instant.now()).toMillis()).orElse(0L)) .messages(totalMessages.orElse(0L)) .errors(failedMessages.orElse(0L)) .topIntegrations(getTopIntegrations()) .build(); } protected PrometheusMetricsProviderImpl(PrometheusConfigurationProperties config, NamespacedOpenShiftClient openShiftClient); @PostConstruct void init(); @PreDestroy void destroy(); @Override IntegrationMetricsSummary getIntegrationMetricsSummary(String integrationId); @Override IntegrationMetricsSummary getTotalIntegrationMetricsSummary(); static final String OPERATOR_TOPK; static final String MIN; static final String MAX; }### Answer: @Test public void testGetTotalIntegrationMetricsSummary() throws Exception { final IntegrationMetricsSummary summary = metricsProvider.getTotalIntegrationMetricsSummary(); assertThat(summary.getMessages()).isNotNull(); final Optional<List<IntegrationDeploymentMetrics>> deploymentMetrics = summary .getIntegrationDeploymentMetrics(); assertThat(deploymentMetrics).isEmpty(); }
### Question: PodMetricsReader implements Runnable { @Override public void run() { try { LOGGER.debug("Collecting stats from integrationId: {}", integrationId); List<Map<String, String>> routeStats = getRoutes(integration, "[a-zA-z0-9_-]+"); routeStats.forEach( m -> { long messages = toLong(m.getOrDefault(EXCHANGES_TOTAL, "0")); long errors = toLong(m.getOrDefault(EXCHANGES_FAILED, "0")); Instant lastCompleted = toInstant(m.get(LAST_COMPLETED_TIMESTAMP)); Instant lastFailed = toInstant(m.get(LAST_FAILED_TIMESTAMP)); Instant lastMessage = (lastCompleted == null && lastFailed != null) || (lastCompleted != null && lastFailed != null && lastFailed.isAfter(lastCompleted)) ? lastFailed : lastCompleted; Instant resetDate = toInstant(m.get(RESET_TIMESTAMP)); Instant startDate = toInstant(m.get(START_TIMESTAMP)); handler.persist(new RawMetrics.Builder() .pod(pod) .integrationId(integrationId) .version(version) .messages(messages) .errors(errors) .startDate(startDate) .lastProcessed(Optional.ofNullable(lastMessage)) .resetDate(resetDate) .build()); } ); } catch (MalformedObjectNameException | J4pException e) { LOGGER.error("Collecting stats from integrationId: {}", integrationId); LOGGER.debug("Collecting stats from integrationId: {}", integrationId, e); } } PodMetricsReader(KubernetesClient kubernetes, String pod, String integration, String integrationId, String version, RawMetricsHandler handler); @Override void run(); List<Map<String, String>> getRoutes(String camelContextName, String filter); static String removeLeadingAndEndingQuotes(String s); static boolean isEmpty(Object value); @SuppressWarnings("unchecked") static boolean isNotEmpty(Object value); }### Answer: @Test @Ignore public void readTest() { String podName = "dbtest1-2-3nvf3"; String integration = "DBTest1"; String integrationId = "-L5ApZneYNfmLWG-PKQt"; String version = "1"; PodMetricsReader reader = new PodMetricsReader( new DefaultKubernetesClient(), podName, integration, integrationId, version, new LogRawMetrics()); reader.run(); }
### Question: MetricsCollector implements Runnable, Closeable { @Override public void close() throws IOException { LOGGER.info("Stopping metrics collector."); close(scheduler); close(executor); } @Autowired MetricsCollector(DataManager dataManager, JsonDB jsonDB, KubernetesClient kubernetes); @PostConstruct @SuppressWarnings("FutureReturnValueIgnored") void open(); @Override void close(); @Override void run(); }### Answer: @Test public void testGetRawMetrics() throws IOException { MetricsCollector collector = new MetricsCollector(null, jsondb, null); Map<String,RawMetrics> metrics = jsondbRM.getRawMetrics("intId1"); assertThat(metrics.size()).isEqualTo(3); assertThat(metrics.keySet()).contains("HISTORY1"); Set<String> livePodIds = new HashSet<>(Arrays.asList("pod1")); jsondbRM.curate("intId1", metrics, livePodIds); Map<String,RawMetrics> metrics2 = jsondbRM.getRawMetrics("intId1"); assertThat(metrics2.size()).isEqualTo(2); assertThat(metrics2.keySet()).contains("HISTORY1"); collector.close(); } @Test public void testGetIntegrationSummary() throws IOException, ParseException { String integrationId = "intId1"; Set<String> livePodIds = new HashSet<String>( Arrays.asList("pod1", "pod2", "pod3", "pod4", "pod5")); MetricsCollector collector = new MetricsCollector(null, jsondb, null); Map<String,RawMetrics> metrics = jsondbRM.getRawMetrics(integrationId); IntegrationMetricsSummary summary = intMH .compute(integrationId, metrics, livePodIds); assertThat(summary.getMessages()).isEqualTo(9); assertThat(summary.getErrors()).isEqualTo(3); assertThat(summary.getStart().get()).isEqualTo(ZonedDateTime.of(2018, 01, 31, 10, 20, 56, 0, ZoneId.of("Z")).toInstant()); jsondb.update(JsonDBRawMetrics.path("intId1","pod2"), JsonUtils.writer().writeValueAsString(raw("intId1","2","pod2",9L,"31-01-2018 10:22:56"))); Map<String,RawMetrics> updatedMetrics = jsondbRM.getRawMetrics(integrationId); IntegrationMetricsSummary updatedSummary = intMH .compute(integrationId, updatedMetrics, livePodIds); assertThat(updatedSummary.getMessages()).isEqualTo(15); assertThat(updatedSummary.getErrors()).isEqualTo(3); collector.close(); } @Test public void testDeadPodCurator() throws IOException, ParseException { String integrationId = "intId1"; MetricsCollector collector = new MetricsCollector(null, jsondb, null); Set<String> livePodIds = new HashSet<String>( Arrays.asList("pod2", "pod3", "pod4", "pod5")); jsondb.update(JsonDBRawMetrics.path("intId1","pod1"), JsonUtils.writer().writeValueAsString(raw("intId1","1","pod1",12L,"31-01-2018 10:22:56"))); Map<String,RawMetrics> metrics = jsondbRM.getRawMetrics(integrationId); IntegrationMetricsSummary summary = intMH .compute(integrationId, metrics, livePodIds); assertThat(summary.getMessages()).isEqualTo(18); assertThat(summary.getErrors()).isEqualTo(3); assertThat(summary.getStart().get()).isEqualTo(ZonedDateTime.of(2018, 01, 31, 10, 22, 56, 0, ZoneId.of("Z")).toInstant()); collector.close(); }