auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static String getSSOTicket(String url, String username, String password, String ticketHeader) throws IOException { String ticket = null; httpClient = new CommonHttpClientBuilder().allowAnyCertificate(true).build(); HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); if ((httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) || (null == httpResponse.getEntity())) throw new IAMException("Authentication failed"); Header[] headers = httpResponse.getHeaders(ticketHeader); if (headers[0] != null) { Pattern pattern = Pattern.compile("(TGT-\\d+-\\S+)"); Matcher matcher = pattern.matcher(headers[0].toString()); if (matcher.find()) { ticket = matcher.group(1); } else throw new IAMException("TGT not found in IAM response"); } logger.debug("Token successfully generated for user " + username + "\n Token: " + ticket); httpClient.close(); return ticket; }

Target:
public String getSSOTicket(String url, String username, String password, String ticketHeader) { String ticket = null; try (CloseableHttpClient httpClient = new CommonHttpClientBuilder().allowAnyCertificate(true).build()) { HttpPost httpPost = new HttpPost(url); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); if ((httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) || (null == httpResponse.getEntity())) { throw new IAMException("Failed to acquire SSO ticket for the user" + username); } Header[] headers = httpResponse.getHeaders(ticketHeader); if (headers[0] != null) { Pattern pattern = Pattern.compile("(TGT-\\d+-\\S+)"); Matcher matcher = pattern.matcher(headers[0].toString()); if (matcher.find()) { ticket = matcher.group(1); } else { throw new IAMException("TGT not found in IAM response"); } } LOG.debug("SSO ticket successfully generated for user " + username + "\n Token: " + ticket); } catch (Exception e) { throw new IAMException("Authentication failed: Error occurred while acquiring SSO ticket for the user " + username, e); } return ticket; }
Source:
public BuiltinList uadd(BitVector<BigInteger> bitVector) { BigInteger result = signedValue().add(bitVector.signedValue()); return new BuiltinList(ImmutableList.<Term>of( BitVector.of(result, bitwidth), BoolToken.of(checkUnsignedOverflow(result)))); }

Target:
public BuiltinList uadd(BitVector<BigInteger> bitVector) { BigInteger result = unsignedValue().add(bitVector.unsignedValue()); return getBuiltinList(result, checkUnsignedOverflow(result)); }
Source:
public static IService getService(IServerAttributes server, Connection connection) { String uniqueId = getAttribute(ATTR_SERVICE, server); if (StringUtils.isEmpty(uniqueId)) { return null; } if( connection == null ) { return null; } String projectName = OpenShiftResourceUniqueId.getProjectName(uniqueId); List<IService> services = connection.getResources(ResourceKind.SERVICE, projectName); IService service = OpenShiftResourceUniqueId.getByUniqueId(uniqueId, services); WatchManager.getInstance().startWatch(service.getProject(), connection); return service; }

Target:
public static IService getService(IServerAttributes server, Connection connection) { String uniqueId = getAttribute(ATTR_SERVICE, server); if (StringUtils.isEmpty(uniqueId)) { return null; } if( connection == null ) { return null; } String projectName = OpenShiftResourceUniqueId.getProjectName(uniqueId); List<IService> services = connection.getResources(ResourceKind.SERVICE, projectName); IService service = OpenShiftResourceUniqueId.getByUniqueId(uniqueId, services); if (server != null) { WatchManager.getInstance().startWatch(service.getProject(), connection); } return service; }
Source:
public void runAfterDelay() throws Exception { CountDownLatch cdl1 = new CountDownLatch(1); CountDownLatch cdl2 = new CountDownLatch(1); long delayMs = 30; long before = System.nanoTime(); DelayedExecutionThread det = new DelayedExecutionThread(delayMs, TimeUnit.MILLISECONDS, () -> { cdl1.countDown(); Uninterruptibles.awaitUninterruptibly(cdl2); }); State state = det.state(); assertTrue("State not not started: " + state, state == State.NOT_STARTED); det.start(); assumeTrue(System.nanoTime() - before < TimeUnit.MILLISECONDS.toNanos(delayMs)); cdl1.await(); assertTrue("Executed too early", System.nanoTime() - before >= TimeUnit.MILLISECONDS.toNanos(delayMs)); state = det.state(); assertTrue("State not running: " + state, state == State.RUNNING); assertEquals(0, cdl1.getCount()); state = det.state(); assertTrue("State not correct: " + state, state == State.COMPLETED || state == State.RUNNING); }

Target:
public void runAfterDelay() throws Exception { CountDownLatch cdl1 = new CountDownLatch(1); CountDownLatch cdl2 = new CountDownLatch(1); long delayMs = 30; long before = System.nanoTime(); DelayedExecutionThread det = new DelayedExecutionThread(delayMs, TimeUnit.MILLISECONDS, () -> { cdl1.countDown(); Uninterruptibles.awaitUninterruptibly(cdl2); }); State state = det.state(); assertTrue("State not not started: " + state, state == State.NOT_STARTED); det.start(); assumeTrue(System.nanoTime() - before < TimeUnit.MILLISECONDS.toNanos(delayMs)); cdl1.await(); assertTrue("Executed too early", System.nanoTime() - before >= TimeUnit.MILLISECONDS.toNanos(delayMs)); state = det.state(); assertTrue("State not running: " + state, state == State.RUNNING); cdl2.countDown(); det.waitUntilDone(); state = det.state(); assertTrue("State not completed: " + state, state == State.COMPLETED); }
Source:
public LogFixture(Logger logger, Level level) { this.logger = logger; logger.addAppender(this); logger.setLevel(level); }

Target:
private LogFixture(Logger logger, Level level) { this.logger = logger; logger.addAppender(this); logger.setLevel(level); }
Source:
public void testCreateViewTimestamp() throws Exception { Properties props = new Properties(); final String schemaName = "S_" + generateUniqueName(); final String tableName = "T_" + generateUniqueName(); final String viewName = "V_" + generateUniqueName(); final String dataTableFullName = SchemaUtil.getTableName(schemaName, tableName); final String viewFullName = SchemaUtil.getTableName(schemaName, viewName); String tableDDL = "CREATE TABLE " + dataTableFullName + " (\n" + "ID1 VARCHAR(15) NOT NULL,\n" + "ID2 VARCHAR(15) NOT NULL,\n" + "CREATED_DATE DATE,\n" + "CREATION_TIME BIGINT,\n" + "LAST_USED DATE,\n" + "CONSTRAINT PK PRIMARY KEY (ID1, ID2)) "; String viewDDL = "CREATE VIEW " + viewFullName + " AS SELECT * " + "FROM " + dataTableFullName; long startTS = EnvironmentEdgeManager.currentTimeMillis(); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { conn.createStatement().execute(tableDDL); conn.createStatement().execute(viewDDL); conn.commit(); CreateTableIT.verifyLastDDLTimestamp(schemaName, viewName, viewFullName, startTS, conn); } }

Target:
public void testCreateViewTimestamp() throws Exception { String tenantId = null; createViewTimestampHelper(tenantId); }
Source:
public static Map<Column, TypeConverter<?, ?>> autoDetectConverters(DataContext dataContext, final List<Column> columns, int sampleSize) { final Map<Column, TypeConverter<?, ?>> result = new HashMap<Column, TypeConverter<?, ?>>(); columns.stream() .filter(col -> col.getType() != null) .filter(col -> col.getType().getSuperType().equals(SuperColumnType.LITERAL_TYPE)) .collect(Collectors.toMap(Column::getTable,Arrays::asList)) .forEach((tab, cols) ->{ autoDetectConvertersInternally(dataContext,tab,cols,sampleSize,result); }); return result; }

Target:
public static Map<Column, TypeConverter<?, ?>> autoDetectConverters(DataContext dataContext, final List<Column> columns, int sampleSize) { final Map<Column, TypeConverter<?, ?>> result = new HashMap<Column, TypeConverter<?, ?>>(); columns.stream() .filter(col -> col.getType() != null) .filter(col -> col.getType().getSuperType().equals(SuperColumnType.LITERAL_TYPE)) .collect(Collectors.toMap(Column::getTable,Arrays::asList)) .forEach((tab, cols) -> autoDetectConvertersInternally(dataContext,tab,cols,sampleSize,result)); return result; }
Source:
public void tearDown() throws Exception { if (executor != null) executor.shutdownNow(); if (app != null) Entities.destroyAll(app.getManagementContext()); if (exampleEntity != null) Entities.destroyAll(exampleEntity.getApplication().getManagementContext()); }

Target:
public void tearDown() throws Exception { if (executor != null) executor.shutdownNow(); if (app != null) Entities.destroyAll(app.getManagementContext()); if (exampleEntity != null && exampleEntity.getApplication() != null) Entities.destroyAll(exampleEntity.getApplication().getManagementContext()); }
Source:
private boolean checkPagingSpec(PagingSpec pagingSpec, boolean descending) { for (Integer value : pagingSpec.getPagingIdentifiers().values()) { if (descending ^ value < 0) { return false; } } return pagingSpec.getThreshold() >= 0; }

Target:
private boolean checkPagingSpec(PagingSpec pagingSpec, boolean descending) { for (Integer value : pagingSpec.getPagingIdentifiers().values()) { if (descending ^ (value < 0)) { return false; } } return pagingSpec.getThreshold() >= 0; }
Source:
private void getPrecipitationHeight_CubicChunks_Replace(BlockPos pos, CallbackInfoReturnable<BlockPos> cbi) { if (isColumn) { BlockPos ret = new BlockPos(pos.getX(), getHeightValue(blockToLocal(pos.getZ()), blockToLocal(pos.getZ())), pos.getZ()); cbi.setReturnValue(ret); cbi.cancel(); } }

Target:
private void getPrecipitationHeight_CubicChunks_Replace(BlockPos pos, CallbackInfoReturnable<BlockPos> cbi) { if (isColumn) { BlockPos ret = new BlockPos(pos.getX(), getHeightValue(blockToLocal(pos.getX()), blockToLocal(pos.getZ())), pos.getZ()); cbi.setReturnValue(ret); cbi.cancel(); } }
Source:
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request) .doOnNext(t -> logger.info("Azure Identity => Attempted credential returns a token", p.getClass().getSimpleName())) .onErrorResume(CredentialUnavailableException.class, t -> { exceptions.add(t); logger.info("Azure Identity => Attempted credential is unavailable.", p.getClass().getSimpleName()); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { StringBuilder message = new StringBuilder("Tried " + credentials.stream().map(c -> c.getClass().getSimpleName()) .collect(Collectors.joining(", ")) + " but failed to acquire a token for any of them. Please verify the" + " environment for the credentials" + " and see more details in the causes below."); CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage(), last); } return Mono.error(new CredentialUnavailableException(message.toString(), last)); })); }

Target:
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request) .doOnNext(t -> logger.info("Azure Identity => Attempted credential returns a token", p.getClass().getSimpleName())) .onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); logger.info("Azure Identity => Attempted credential is unavailable.", p.getClass().getSimpleName()); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
Source:
public void init(Map<String, Object> conf, SinkContext context) { String path = (String) conf.get(KEY_PATH); String portFile = (String) conf.get(KEY_PORT_FILE); isFlatMetrics = TypeUtils.getBoolean(conf.getOrDefault(KEY_FLAT_METRICS, true)); includeServiceNamespace = TypeUtils.getBoolean( conf.getOrDefault(KEY_INCLUDE_TOPOLOGY_NAME, false)); topologyName = context.getTopologyName(); int port = TypeUtils.getInteger(conf.getOrDefault(KEY_PORT, 0)); if (port == 0) { if (portFile != null) { try { port = TypeUtils.getInteger(Files.lines(Paths.get(portFile)).findFirst().get().trim()); } catch (IOException e) { throw new IllegalArgumentException("Could not parse " + KEY_PORT_FILE + " " + portFile + " Make sure the file only contains the port on which the service should run" + " and is UTF8 encoded", e); } } else { throw new IllegalArgumentException("Neither 'port' nor 'port_file' " + "were specified in config for metrics sink " + context.getSinkId()); } } startHttpServer(path, port); }

Target:
public void init(Map<String, Object> conf, SinkContext context) { String path = (String) conf.get(KEY_PATH); String portFile = (String) conf.get(KEY_PORT_FILE); isFlatMetrics = TypeUtils.getBoolean(conf.getOrDefault(KEY_FLAT_METRICS, true)); includeTopologyName = TypeUtils.getBoolean( conf.getOrDefault(KEY_INCLUDE_TOPOLOGY_NAME, false)); long cacheMaxSize = TypeUtils.getLong(conf.getOrDefault(KEY_METRICS_CACHE_MAX_SIZE, 1000000)); long cacheTtlSec = TypeUtils.getLong(conf.getOrDefault(KEY_METRICS_CACHE_TTL_SEC, 600)); metricsCache = CacheBuilder.newBuilder() .maximumSize(cacheMaxSize) .expireAfterWrite(cacheTtlSec, TimeUnit.SECONDS) .build(); topologyName = context.getTopologyName(); int port = TypeUtils.getInteger(conf.getOrDefault(KEY_PORT, 0)); if (port == 0) { if (!Strings.isNullOrEmpty(portFile)) { try { port = TypeUtils.getInteger(Files.lines(Paths.get(portFile)).findFirst() .get().trim()); } catch (IOException | SecurityException | IllegalArgumentException e) { throw new IllegalArgumentException("Could not parse " + KEY_PORT_FILE + " " + portFile + " Make sure the file is readable," + " only contains the port on which the service should run" + " and is UTF8 encoded", e); } } else { throw new IllegalArgumentException("Neither 'port' nor 'port_file' " + "were specified in config for metrics sink " + context.getSinkId()); } } startHttpServer(path, port); }
Source:
public String getWebviewDevtoolsPort() { return (String) getCapability(AndroidMobileCapabilityType.WEBVIEW_DEVTOOLS_PORT); }

Target:
public Integer getWebviewDevtoolsPort() { return (Integer) getCapability(AndroidMobileCapabilityType.WEBVIEW_DEVTOOLS_PORT); }
Source:
void create() { logger.info("Cache getting created."); statusTransitioner.checkMaintenance(); try { store.create(); } catch (CacheAccessException e) { throw new RuntimeException("Couldn't create Cache", e); } logger.info("Cache successfully created."); }

Target:
void create() { logger.info("Creating Cache storage."); statusTransitioner.checkMaintenance(); try { store.create(); } catch (CacheAccessException e) { throw new RuntimeException("Couldn't create Cache storage ", e); } logger.info("Cache storage successfully created."); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((WordPress) getApplication()).component().inject(this); setContentView(R.layout.login_activity); if (!hasLoginNavFragment()) { addLoginNavFragment(); } if (savedInstanceState == null) { addLoginPrologueFragment(); } }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((WordPress) getApplication()).component().inject(this); setContentView(R.layout.login_activity); if (!hasLoginNavFragment()) { addLoginNavFragment(); } if (!hasLoginEmailCheckerFragment()) { addLoginEmailCheckerFragment(); } if (savedInstanceState == null) { addLoginPrologueFragment(); } }
Source:
public void parsePropertyFiles_OnInvalidFilePath_ThrowsException() { final String invalidFile = "?on-invalid-file-path.properties"; initWithProperties(EMPTY_PROPERTIES); propertyReports.add(invalidFile); ReportParser reportParser = new ReportParser(configuration); thrown.expect(ValidationException.class); thrown.expectMessage(containsString(invalidFile)); thrown.expectMessage(endsWith("doesn't exist or the properties file is invalid!")); reportParser.parsePropertiesFiles(propertyReports); }

Target:
public void parsePropertyFiles_OnInvalidFilePath_ThrowsException() { final String invalidFile = "?on-invalid-file-path.properties"; initWithProperties(EMPTY_PROPERTIES); classificationFiles.add(invalidFile); ReportParser reportParser = new ReportParser(configuration); thrown.expect(ValidationException.class); thrown.expectMessage(containsString(invalidFile)); thrown.expectMessage(endsWith("doesn't exist or the properties file is invalid!")); reportParser.parseClassificationsFiles(classificationFiles); }
Source:
public Inbox<I> build() { Delivery delivery = ServerEnvironment.instance() .delivery(); checkNotNull(entityStateType, "Entity state type must be set"); checkArgument(!eventEndpoints.isEmpty() || !commandEndpoints.isEmpty(), "There must be at least one event or command endpoint"); Inbox<I> inbox = new Inbox<>(this, delivery); delivery.register(inbox); return inbox; }

Target:
public Inbox<I> build() { Delivery delivery = ServerEnvironment.instance() .delivery(); checkNotNull(entityStateType, "Entity state type must be set."); checkArgument(!eventEndpoints.isEmpty() || !commandEndpoints.isEmpty(), "There must be at least one event or command endpoint."); Inbox<I> inbox = new Inbox<>(this, delivery); delivery.register(inbox); return inbox; }
Source:
private SCMs mergeScms() { SCMs scms = BasicCruiseConfig.this.scms; for (PartialConfig part : this.parts) { scms.addAll(part.getScms()); } return scms; }

Target:
private SCMs mergeScms() { SCMs scms = new SCMs(); scms.addAll(BasicCruiseConfig.this.scms); for (PartialConfig part : this.parts) { scms.addAll(part.getScms()); } SCMs mergedScms = new SCMs(); for (SCM scm : scms) { if (forEdit) { if (scm.isLocal()) { mergedScms.add(scm); } } else { mergedScms.add(scm); } } return mergedScms; }
Source:
public void deleteFromRealm_twice() { realm.beginTransaction(); snapshot.deleteFromRealm(0); snapshot.deleteFromRealm(0); realm.commitTransaction(); }

Target:
public void deleteFromRealm_twice() { realm.beginTransaction(); snapshot.deleteFromRealm(0); snapshot.deleteFromRealm(0); realm.commitTransaction(); assertFalse(snapshot.get(0).isValid()); }
Source:
private void registerIndexEditor(BundleContext bundleContext, IndexTracker tracker, LuceneIndexMBean mBean, Map<String, ?> config) throws IOException { boolean enableCopyOnWrite = PropertiesUtil.toBoolean(config.get(PROP_COPY_ON_WRITE), PROP_COPY_ON_WRITE_DEFAULT); if (enableCopyOnWrite){ initializeIndexCopier(bundleContext, config); editorProvider = new LuceneIndexEditorProvider(indexCopier, tracker, extractedTextCache, augmentorFactory, mountInfoProvider, activeDeletedBlobCollector, mBean, statisticsProvider) .withAsyncIndexesSizeStatsUpdate(asyncIndexesSizeStatsUpdate); log.info("Enabling CopyOnWrite support. Index files would be copied under {}", indexDir.getAbsolutePath()); } else { editorProvider = new LuceneIndexEditorProvider(null, tracker, extractedTextCache, augmentorFactory, mountInfoProvider, activeDeletedBlobCollector, mBean, statisticsProvider) .withAsyncIndexesSizeStatsUpdate(asyncIndexesSizeStatsUpdate); } editorProvider.setBlobStore(blobStore); if (hybridIndex){ editorProvider.setIndexingQueue(checkNotNull(documentQueue)); } Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put("type", TYPE_LUCENE); regs.add(bundleContext.registerService(IndexEditorProvider.class.getName(), editorProvider, props)); oakRegs.add(registerMBean(whiteboard, TextExtractionStatsMBean.class, editorProvider.getExtractedTextCache().getStatsMBean(), TextExtractionStatsMBean.TYPE, "TextExtraction statistics")); }

Target:
private void registerIndexEditor(BundleContext bundleContext, IndexTracker tracker, LuceneIndexMBean mBean, Map<String, ?> config) throws IOException { boolean enableCopyOnWrite = PropertiesUtil.toBoolean(config.get(PROP_COPY_ON_WRITE), PROP_COPY_ON_WRITE_DEFAULT); if (enableCopyOnWrite){ initializeIndexCopier(bundleContext, config); editorProvider = new LuceneIndexEditorProvider(indexCopier, tracker, extractedTextCache, augmentorFactory, mountInfoProvider, activeDeletedBlobCollector, mBean, statisticsProvider); log.info("Enabling CopyOnWrite support. Index files would be copied under {}", indexDir.getAbsolutePath()); } else { editorProvider = new LuceneIndexEditorProvider(null, tracker, extractedTextCache, augmentorFactory, mountInfoProvider, activeDeletedBlobCollector, mBean, statisticsProvider); } editorProvider.setBlobStore(blobStore); editorProvider.withAsyncIndexesSizeStatsUpdate(asyncIndexesSizeStatsUpdate); if (hybridIndex){ editorProvider.setIndexingQueue(checkNotNull(documentQueue)); } Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put("type", TYPE_LUCENE); regs.add(bundleContext.registerService(IndexEditorProvider.class.getName(), editorProvider, props)); oakRegs.add(registerMBean(whiteboard, TextExtractionStatsMBean.class, editorProvider.getExtractedTextCache().getStatsMBean(), TextExtractionStatsMBean.TYPE, "TextExtraction statistics")); }
Source:
public static void setUp() throws Exception { File availableClaimsFile = testFolder.newFile("attributeMap.properties"); availableClaimsFilePath = availableClaimsFile.getCanonicalPath(); Properties availableClaims = new Properties(); availableClaims.put("testClaim1", "testValue1"); availableClaims.put("testClaim2", "testValue2"); availableClaims.put("testClaim3", "testValue3"); availableClaims.store(new FileWriter(availableClaimsFile), "test"); File profilesJson = testFolder.newFile("profiles.json"); profilesDotJsonPath = profilesJson.getCanonicalPath(); Map<String, Object> outterMap = new HashMap<>(); Map<String, Object> profile1Map = new HashMap<>(); Map<String, Object> profile2Map = new HashMap<>(); outterMap.put("profile1", ImmutableMap.of(GUEST_CLAIMS, profile1Map)); outterMap.put("profile2", ImmutableMap.of(GUEST_CLAIMS, profile2Map)); profile1Map.put("testClaim1", "profile1Value1"); profile1Map.put("testClaim2", "profile1Value2"); profile1Map.put("testClaim3", "profile1Value3"); profile1Map.put("testClaim4", "profile1Value4"); profile2Map.put("testClaim1", "profile2Value1"); profile2Map.put("testClaim2", "profile2Value2"); profile2Map.put("testClaim3", "profile2Value3"); profile2Map.put("testClaim4", "profile2Value4"); String json = GSON.toJson(outterMap); FileUtils.write(profilesJson, json); }

Target:
public static void setUp() throws Exception { File availableClaimsFile = testFolder.newFile("attributeMap.properties"); try (InputStream is = GuestClaimsHandlerExtTest.class.getResourceAsStream("/attributeMap.properties")) { FileUtils.copyToFile(is, availableClaimsFile); } availableClaimsFilePath = availableClaimsFile.getCanonicalPath(); File profilesJson = testFolder.newFile("profiles.json"); try (InputStream is = GuestClaimsHandlerExtTest.class.getResourceAsStream("/profiles.json")) { FileUtils.copyToFile(is, profilesJson); } profilesDotJsonPath = profilesJson.getCanonicalPath(); }
Source:
public void validateRelayState(String relayState, boolean strictRelayState) { LOGGER.debug("Validating RelayState"); if (relayState != null && relayState.length() > 80) { if (strictRelayState) { throw new IllegalArgumentException("RelayState must be 80 bytes or shorter"); } else { LOGGER.warn("RelayState has invalid size: {}", relayState.length()); } } if (relayState != null && (relayState.contains("<") || relayState.contains(">"))) { throw new IllegalArgumentException("RelayState cannot contain '<' or '>'"); } }

Target:
public void validateRelayState(String relayState, boolean strictRelayState) { LOGGER.debug("Validating RelayState"); if (relayState != null && relayState.length() > 80) { LOGGER.warn("RelayState has invalid size: {}", relayState.length()); if (strictRelayState) { throw new IllegalArgumentException("RelayState must be 80 bytes or shorter"); } } if (relayState != null && (relayState.contains("<") || relayState.contains(">"))) { throw new IllegalArgumentException("RelayState cannot contain '<' or '>'"); } }
Source:
public static boolean isPrime(long val) { return API.Match(val).of( Case($(2L), true), Case($(n -> n > 2), n -> !primes().takeWhile(d -> d <= Math.sqrt(n)).exists(d -> n % d == 0)), Case($(), false) ); }

Target:
public static boolean isPrime(long val) { return API.Match(val).of( Case($(2L), true), Case($(n -> n > 2), n -> { final double upperLimitToCheck = Math.sqrt(n); return !primes().takeWhile(d -> d <= upperLimitToCheck).exists(d -> n % d == 0); }), Case($(), false) ); }
Source:
private void setup() { random = new Random(); hadoopConf = new Configuration(); hadoopConf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); hadoopConf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); listDirectoryOperation = path -> { FileSystem fs = path.getFileSystem(hadoopConf); return new HadoopDirectoryLister.HadoopFileInfoIterator(fs.listLocatedStatus(path)); }; }

Target:
private void setup() { hadoopConf = new Configuration(); hadoopConf.set("fs.hdfs.impl", org.apache.hadoop.hdfs.DistributedFileSystem.class.getName()); hadoopConf.set("fs.file.impl", org.apache.hadoop.fs.LocalFileSystem.class.getName()); listDirectoryOperation = path -> { FileSystem fs = path.getFileSystem(hadoopConf); return new HadoopFileInfoIterator(fs.listLocatedStatus(path)); }; }
Source:
public static GitPerson toGitPerson(UserIdentity committer) { GitPerson p = new GitPerson(); p.name = committer.getName(); p.email = committer.getEmail(); p.date = committer.getDate(); p.tz = committer.getTimeZone(); return p; }

Target:
private static GitPerson toGitPerson(UserIdentity committer) { GitPerson p = new GitPerson(); p.name = committer.getName(); p.email = committer.getEmail(); p.date = committer.getDate(); p.tz = committer.getTimeZone(); return p; }
Source:
public boolean unloadQueuedChunks() { if (this.worldServer.getDisableLevelSaving()) { return false; } final int MaxNumToUnload = 400; Iterator<CubeCoords> iter = this.cubesToUnload.iterator(); while (iter.hasNext()) { CubeCoords coords = iter.next(); if (this.dependencyManager.isRequired(coords)) { continue; } long columnAddress = AddressTools.getAddress(coords.getCubeX(), coords.getCubeZ()); Column column = this.loadedColumns.get(columnAddress); if (column == null) { continue; } Cube cube = column.removeCube(coords.getCubeY()); if (cube != null) { this.recursivelyRemoveForceLoadedCube(cube); cube.onUnload(); this.worldServer.getGeneratorPipeline().getDependentCubeManager().unregister(cube); this.cubeIO.saveCube(cube); } if (!column.hasCubes()) { column.onChunkUnload(); this.loadedColumns.remove(columnAddress); this.cubeIO.saveColumn(column); } iter.remove(); } return false; }

Target:
public boolean unloadQueuedChunks() { if (this.worldServer.getDisableLevelSaving()) { return false; } final int MaxNumToUnload = 400; Iterator<CubeCoords> iter = this.cubesToUnload.iterator(); int processed = 0; while (iter.hasNext() && processed < MaxNumToUnload) { CubeCoords coords = iter.next(); if (this.dependencyManager.isRequired(coords)) { continue; } long columnAddress = AddressTools.getAddress(coords.getCubeX(), coords.getCubeZ()); Column column = this.loadedColumns.get(columnAddress); if (column == null) { continue; } Cube cube = column.removeCube(coords.getCubeY()); if (cube != null) { this.recursivelyRemoveForceLoadedCube(cube); cube.onUnload(); this.worldServer.getGeneratorPipeline().getDependentCubeManager().unregister(cube); this.cubeIO.saveCube(cube); } if (!column.hasCubes()) { column.onChunkUnload(); this.loadedColumns.remove(columnAddress); this.cubeIO.saveColumn(column); } iter.remove(); ++processed; } return false; }
Source:
private void castSubType( String typeName, Type type, Value value, StringBuilder pathBuilder ) throws TypeCastingException { pathBuilder.append( '.' ); pathBuilder.append( typeName ); boolean hasChildren = value.hasChildren( typeName ); if ( hasChildren == false && type.cardinality().min() > 0 && !(type instanceof TypePair) ) { throw new TypeCastingException( "Undefined required child node: " + pathBuilder.toString() ); } else if ( hasChildren ) { ValueVector vector = value.getChildren( typeName ); int size = vector.size(); if (!(type instanceof TypePair ) && checkCardinality(type, size)) { throw new TypeCastingException( "Child node " + pathBuilder.toString() + " has a wrong number of occurencies. Permitted range is [" + type.cardinality().min() + "," + type.cardinality().max() + "], found " + size ); } for( Value v : vector ) { type.cast( v, pathBuilder ); } } }

Target:
private void castSubType( String typeName, Type type, Value value, StringBuilder pathBuilder ) throws TypeCastingException { pathBuilder.append( '.' ); pathBuilder.append( typeName ); final boolean hasChildren = value.hasChildren( typeName ); if ( hasChildren == false && type.cardinality().min() > 0 ) { throw new TypeCastingException( "Undefined required child node: " + pathBuilder.toString() ); } else if ( hasChildren ) { final ValueVector vector = value.getChildren( typeName ); final int size = vector.size(); if ( type.cardinality().min() > size || type.cardinality().max() < size ) { throw new TypeCastingException( "Child node " + pathBuilder.toString() + " has a wrong number of occurencies. Permitted range is [" + type.cardinality().min() + "," + type.cardinality().max() + "], found " + size ); } for( Value v : vector ) { type.cast( v, pathBuilder ); } } }
Source:
public S3ClientOptions disableChunkedEncoding() { setChunkedEncoding(false); return this; }

Target:
public S3ClientOptions disableChunkedEncoding() { this.chunkedEncodingDisabled = true; return this; }
Source:
public SpringCache getCache(final String name) { return cacheByName.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); }

Target:
public SpringCache getCache(final String name) { return springCaches.computeIfAbsent(name, n -> { final Cache<Object, Object> nativeCache = this.nativeCacheManager.getCache(n); return new SpringCache(nativeCache); }); }
Source:
protected void processIterableBatch(InvocationContext ctx, PutMapCommand cmd, PersistenceManager.AccessMode mode, Predicate<Object> filter) { if (getStatisticsEnabled()) cacheStores.addAndGet(cmd.getMap().size()); Iterator<MarshalledEntry> iterator = cmd.getMap().keySet().stream() .filter(filter) .map(key -> createMarshalledEntry(ctx, key)) .iterator(); if (iterator.hasNext()) { persistenceManager.writeBatchToAllNonTxStores(() -> iterator, mode, cmd.getFlagsBitSet()); } }

Target:
protected void processIterableBatch(InvocationContext ctx, PutMapCommand cmd, PersistenceManager.AccessMode mode, Predicate<Object> filter) { if (getStatisticsEnabled()) cacheStores.addAndGet(cmd.getMap().size()); Iterable<MarshalledEntry> iterable = () -> cmd.getMap().keySet().stream() .filter(filter) .map(key -> createMarshalledEntry(ctx, key)) .iterator(); persistenceManager.writeBatchToAllNonTxStores(iterable, mode, cmd.getFlagsBitSet()); }
Source:
protected boolean validate() { setStoragePoolId(getVm().getStoragePoolId()); if (!isValidParametersList() || !checkImagesStatus() || !validateSpaceRequirements() || !performVmRelatedChecks()) { return false; } for (LiveMigrateDiskParameters parameters : getParameters().getParametersList()) { getReturnValue().setValid(isDiskNotShareable(parameters.getImageId()) && isDiskSnapshotNotPluggedToOtherVmsThatAreNotDown(parameters.getImageId()) && isTemplateInDestStorageDomain(parameters.getImageId(), parameters.getTargetStorageDomainId()) && performStorageDomainsChecks(parameters) && isSameSourceAndDest(parameters)); if (!getReturnValue().isValid()) { return false; } } if (!setAndValidateDiskProfiles()) { return false; } return validateCreateAllSnapshotsFromVmCommand(); }

Target:
protected boolean validate() { setStoragePoolId(getVm().getStoragePoolId()); if (!isValidParametersList() || !validateDestDomainsSpaceRequirements()) { return false; } for (LiveMigrateDiskParameters parameters : getParameters().getParametersList()) { getReturnValue().setValid(isDiskNotShareable(parameters.getImageId()) && isDiskSnapshotNotPluggedToOtherVmsThatAreNotDown(parameters.getImageId()) && isTemplateInDestStorageDomain(parameters.getImageId(), parameters.getTargetStorageDomainId()) && validateDestStorage(getStorageDomainById(parameters.getTargetStorageDomainId(), getStoragePoolId())) && isSameSourceAndDest(parameters)); if (!getReturnValue().isValid()) { return false; } } if (!setAndValidateDiskProfiles()) { return false; } return validateCreateAllSnapshotsFromVmCommand(); }
Source:
private String getAllDataFromObisCode(final LnClientConnection conn, final ClassIdObisAttr obisAttr) throws ProtocolAdapterException, IOException, TimeoutException { String output = ""; final int noOfAttr = obisAttr.getNoAttr(); for (int attributeValue = 1; attributeValue <= noOfAttr; attributeValue++) { LOGGER.info("Creating output for attr: {}/{}", obisAttr.getObisCode().value(), attributeValue, noOfAttr); output += this.getAllDataFromAttribute(conn, obisAttr.getClassNumber(), obisAttr.getObisCode(), attributeValue); } return output; }

Target:
private String getAllDataFromObisCode(final LnClientConnection conn, final ClassIdObisAttr obisAttr) throws ProtocolAdapterException, IOException, TimeoutException { String output = ""; final int noOfAttr = obisAttr.getNoAttr(); for (int attributeValue = 1; attributeValue <= noOfAttr; attributeValue++) { LOGGER.debug("Creating output for attr: {}/{}", obisAttr.getObisCode().value(), attributeValue, noOfAttr); output += this.getAllDataFromAttribute(conn, obisAttr.getClassNumber(), obisAttr.getObisCode(), attributeValue); } return output; }
Source:
public AuthenticationResult getToken(String authorizationUrl) throws Exception { if (StringExtensions.IsNullOrBlank(authorizationUrl)) { throw new IllegalArgumentException("finalUrl"); } HashMap<String, String> parameters = getUrlParameters(authorizationUrl); String encodedState = parameters.get("state"); String state = decodeProtocolState(encodedState); if (!StringExtensions.IsNullOrBlank(state)) { Uri stateUri = Uri.parse("http://state/path?" + state); String authorizationUri = stateUri.getQueryParameter("a"); String resource = stateUri.getQueryParameter("r"); if (!StringExtensions.IsNullOrBlank(authorizationUri) && !StringExtensions.IsNullOrBlank(resource) && resource.equalsIgnoreCase(mRequest.getResource())) { AuthenticationResult result = processUIResponseParams(parameters); if (result != null && result.getStatus() == AuthenticationResult.AuthenticationStatus.Succeeded) { if (!result.getCode().isEmpty()) { return getTokenForCode(result.getCode()); } else if (!StringExtensions.IsNullOrBlank(result.getAccessToken())) { return result; } else { throw new AuthenticationException(ADALError.AUTH_FAILED_NO_TOKEN); } } else { throw new AuthenticationException(ADALError.AUTH_FAILED_NO_TOKEN, result.getErrorCode() + " " + result.getErrorDescription()); } } else { throw new AuthenticationException(ADALError.AUTH_FAILED_BAD_STATE); } } else { throw new AuthenticationException(ADALError.AUTH_FAILED_NO_STATE); } }

Target:
public AuthenticationResult getToken(String authorizationUrl) throws Exception { if (StringExtensions.IsNullOrBlank(authorizationUrl)) { throw new IllegalArgumentException("authorizationUrl"); } HashMap<String, String> parameters = getUrlParameters(authorizationUrl); String encodedState = parameters.get("state"); String state = decodeProtocolState(encodedState); if (!StringExtensions.IsNullOrBlank(state)) { Uri stateUri = Uri.parse("http://state/path?" + state); String authorizationUri = stateUri.getQueryParameter("a"); String resource = stateUri.getQueryParameter("r"); if (!StringExtensions.IsNullOrBlank(authorizationUri) && !StringExtensions.IsNullOrBlank(resource) && resource.equalsIgnoreCase(mRequest.getResource())) { AuthenticationResult result = processUIResponseParams(parameters); if (result != null && result.getStatus() == AuthenticationResult.AuthenticationStatus.Succeeded) { if (!result.getCode().isEmpty()) { return getTokenForCode(result.getCode()); } else if (!StringExtensions.IsNullOrBlank(result.getAccessToken())) { return result; } else { throw new AuthenticationException(ADALError.AUTH_FAILED_NO_TOKEN); } } else { throw new AuthenticationException(ADALError.AUTH_FAILED_NO_TOKEN, result.getErrorCode() + " " + result.getErrorDescription()); } } else { throw new AuthenticationException(ADALError.AUTH_FAILED_BAD_STATE); } } else { throw new AuthenticationException(ADALError.AUTH_FAILED_NO_STATE); } }
Source:
public ByteArrayBufferImpl(byte[] buffer, int offset, int length) { this.buffer = Objects.requireNonNull(buffer, "buffer"); if (offset + length > buffer.length) { throw new IllegalArgumentException("length"); } this.offset = offset; this.length = length; }

Target:
public ByteArrayBufferImpl(byte[] buffer, int offset, int length) { this.buffer = Objects.requireNonNull(buffer, "buffer"); if (offset + length > buffer.length || length < 0 || offset < 0) { throw new IllegalArgumentException("length or offset"); } this.offset = offset; this.length = length; }
Source:
public void afterRefreshTreatment(boolean succeeded) { try { synchronized (this) { if (succeeded) { unrespondedAttempts.set(0); setLastUpdate(); Guid storagePoolId = null; ArrayList<VDSDomainsData> domainsList = null; try { hostMonitoring.afterRefreshTreatment(); if (cachedVds != null && cachedVds.getStatus() != VDSStatus.Maintenance) { storagePoolId = cachedVds.getStoragePoolId(); domainsList = cachedVds.getDomains(); } hostMonitoring = null; } catch (IRSErrorException ex) { logAfterRefreshFailureMessage(ex); if (log.isDebugEnabled()) { logException(ex); } } catch (RuntimeException ex) { logAfterRefreshFailureMessage(ex); logException(ex); } if (domainsList != null) { updateVdsDomainsData(cachedVds, storagePoolId, domainsList); } } } } catch (Exception e) { log.error("Timer update runtime info failed. Exception:", ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception:", e); } finally { lockManager.releaseLock(monitoringLock); } }

Target:
public void afterRefreshTreatment(boolean succeeded) { if (!succeeded) { lockManager.releaseLock(monitoringLock); return; } try { synchronized (this) { unrespondedAttempts.set(0); setLastUpdate(); Guid storagePoolId = null; ArrayList<VDSDomainsData> domainsList = null; try { hostMonitoring.afterRefreshTreatment(); if (cachedVds != null && cachedVds.getStatus() != VDSStatus.Maintenance) { storagePoolId = cachedVds.getStoragePoolId(); domainsList = cachedVds.getDomains(); } hostMonitoring = null; } catch (IRSErrorException ex) { logAfterRefreshFailureMessage(ex); if (log.isDebugEnabled()) { logException(ex); } } catch (RuntimeException ex) { logAfterRefreshFailureMessage(ex); logException(ex); } if (domainsList != null) { updateVdsDomainsData(cachedVds, storagePoolId, domainsList); } } } catch (Exception e) { log.error("Timer update runtime info failed. Exception:", ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception:", e); } finally { lockManager.releaseLock(monitoringLock); } }
Source:
public Boolean isPullSuccessIndicated() { if (getStatus() == null) return false; return (getStatus().contains("Download complete") || getStatus().contains("Image is up to date") || getStatus() .contains("Downloaded newer image")); }

Target:
public boolean isPullSuccessIndicated() { if (isErrorIndicated() || getStatus() == null) { return false; } return (getStatus().contains("Download complete") || getStatus().contains("Image is up to date") || getStatus() .contains("Downloaded newer image")); }
Source:
private String removeUnprintableChars(String text) { StringBuilder stringbuilder = new StringBuilder(); for(char c0 : text.toCharArray()) { if (c0 != 167 && c0 != 127) { stringbuilder.append(c0); } } return stringbuilder.toString(); }

Target:
private String removeUnprintableChars(String text) { StringBuilder stringbuilder = new StringBuilder(); for(char c0 : text.toCharArray()) if (c0 != 167 && c0 != 127) stringbuilder.append(c0); return stringbuilder.toString(); }
Source:
private void addCommitHooks(TaskAttemptContext context, Path outputPath) throws IOException { try { Path workPath = super.getWorkPath(); log.debug("Attaching offset writer hooks"); log.info("Adding offset writer hook: " + SequenceFileOffsetCommitter.class.getCanonicalName()); offsetWriterHooks.add(new SequenceFileOffsetCommitter(workPath, outputPath)); log.debug("Adding user-defined offset writer hooks"); for (Class<?> klass : context.getConfiguration().getClasses(ETL_OFFSET_WRITER_HOOKS)) { log.info("Adding offset writer hook: " + klass.getCanonicalName()); Constructor constructor = klass.getConstructor(Path.class, Path.class); OffsetWriterHook offsetWriterHook = (OffsetWriterHook) constructor.newInstance(workPath, outputPath); offsetWriterHooks.add(offsetWriterHook); } log.debug("All offset writer hooks added"); } catch (Exception e) { throw new IOException(e); } }

Target:
private void addCommitHooks(TaskAttemptContext context, Path outputPath) throws IOException { try { Path workPath = super.getWorkPath(); log.debug("Adding offset writer hook: " + SequenceFileOffsetCommitter.class.getCanonicalName()); commitHooks.add(new SequenceFileOffsetCommitter()); for (Class<?> klass : context.getConfiguration().getClasses(ETL_COMMIT_HOOKS)) { log.debug("Adding offset writer hook: " + klass.getCanonicalName()); Constructor constructor = klass.getConstructor(); CommitHook commitHook = (CommitHook) constructor.newInstance(); commitHooks.add(commitHook); } } catch (Exception e) { throw new IOException(e); } }
Source:
protected void lauchUpdateInstallTask() { InstallStagedUpdateTask<UpdateActivity> task = new InstallStagedUpdateTask<UpdateActivity>(DIALOG_UPGRADE_INSTALL) { @Override protected void deliverResult(UpdateActivity receiver, AppInstallStatus result) { if (result == AppInstallStatus.Installed) { uiState.updateInstalledUiState(); } else { uiState.errorUiState(); } } @Override protected void deliverUpdate(UpdateActivity receiver, int[]... update) { } @Override protected void deliverError(UpdateActivity receiver, Exception e) { uiState.errorUiState(); } }; task.connect(this); task.execute(); }

Target:
protected void lauchUpdateInstallTask() { InstallStagedUpdateTask<UpdateActivity> task = new InstallStagedUpdateTask<UpdateActivity>(DIALOG_UPGRADE_INSTALL) { @Override protected void deliverResult(UpdateActivity receiver, AppInstallStatus result) { if (result == AppInstallStatus.Installed) { receiver.uiState.updateInstalledUiState(); } else { receiver.uiState.errorUiState(); } } @Override protected void deliverUpdate(UpdateActivity receiver, int[]... update) { } @Override protected void deliverError(UpdateActivity receiver, Exception e) { receiver.uiState.errorUiState(); } }; task.connect(this); task.execute(); }
Source:
public Builder(String subject, List<String> addressReceiver, List<String> groupReceiver, Text content) { adminEmailAttributes = new AdminEmailAttributes(); adminEmailAttributes.addressReceiver = addressReceiver; adminEmailAttributes.groupReceiver = groupReceiver; adminEmailAttributes.subject = subject; adminEmailAttributes.content = content; Assumption.assertNotNull("Non-null value expected for required AdminEmailAttributes", adminEmailAttributes.addressReceiver, adminEmailAttributes.groupReceiver, adminEmailAttributes.subject, adminEmailAttributes.content); }

Target:
public Builder(String subject, List<String> addressReceiver, List<String> groupReceiver, Text content) { Assumption.assertNotNull(Const.StatusCodes.NULL_PARAMETER, subject); Assumption.assertNotNull(Const.StatusCodes.NULL_PARAMETER, addressReceiver); Assumption.assertNotNull(Const.StatusCodes.NULL_PARAMETER, groupReceiver); Assumption.assertNotNull(Const.StatusCodes.NULL_PARAMETER, content); adminEmailAttributes = new AdminEmailAttributes(); adminEmailAttributes.addressReceiver = addressReceiver; adminEmailAttributes.groupReceiver = groupReceiver; adminEmailAttributes.subject = subject; adminEmailAttributes.content = content; }
Source:
protected void teardown() { ThreadPoolUtil.execute(() -> { int sleepTimeInSec = Config.<Integer> getValue(ConfigValues.ServerRebootTimeout); log.info("Waiting seconds, for server to finish boot process.", sleepTimeInSec); ThreadUtils.sleep(TimeUnit.SECONDS.toMillis(sleepTimeInSec)); if (getParameters().isChangeHostToMaintenanceOnStart()) { setStatus(VDSStatus.Maintenance); } else { setStatus(VDSStatus.NonResponsive); } }); }

Target:
protected void teardown() { }
Source:
private List<ItemDefinition> itemDefinitions() { return dmnGraphUtils.getDefinitions().getItemDefinition(); }

Target:
private List<ItemDefinition> itemDefinitions() { return itemDefinitionUtils.all(); }
Source:
public void test_JDK7171415() { URI lower = URI.create("<LINK_3>"); URI mixed = URI.create("<LINK_2>"); assertTrue(lower.equals(mixed)); assertEquals(lower.hashCode(), mixed.hashCode()); }

Target:
public void test_JDK7171415() { URI lower, mixed; lower = URI.create("<LINK_3>"); mixed = URI.create("<LINK_2>"); assertTrue(lower.equals(mixed)); assertEquals(lower.hashCode(), mixed.hashCode()); lower = URI.create("<LINK_0>"); mixed = URI.create("<LINK_1>"); assertFalse(lower.equals(mixed)); assertFalse(lower.hashCode() == mixed.hashCode()); }
Source:
private void assertColumnModify(String columnName, String schemaName, String tableName, Integer expectedLenValue, Integer expectedScalaValue, PDataType dataType) throws Exception { String query = "SELECT " + COLUMN_SIZE + ", "+ DECIMAL_DIGITS + "," + COLUMN_FAMILY + "," + DATA_TYPE + " FROM \"SYSTEM\".CATALOG WHERE " + TABLE_SCHEM + " = ? AND " + TABLE_NAME + " = ? AND " + COLUMN_NAME + " = ?" + " AND " + COLUMN_FAMILY + " = ?"; try (Connection conn = DriverManager.getConnection(getUrl())) { PreparedStatement stmt = conn.prepareStatement(query); stmt.setString(1, schemaName); stmt.setString(2, tableName); stmt.setString(3, columnName); stmt.setString(4, QueryConstants.DEFAULT_COLUMN_FAMILY); ResultSet rs = stmt.executeQuery(); assertTrue(rs.next()); if (expectedLenValue != null) { assertEquals(expectedLenValue.intValue(), rs.getInt(1)); } if (expectedScalaValue != null) { assertEquals(expectedScalaValue.intValue(), rs.getInt(2)); } if (dataType != null) { assertEquals(rs.getInt(4), dataType.getSqlType()); } assertFalse(rs.next()); } }

Target:
private void assertColumnModify(String columnName, String schemaName, String tableName, Integer expectedLenValue, Integer expectedScalaValue, PDataType dataType) throws Exception { String query = "SELECT " + COLUMN_SIZE + ", "+ DECIMAL_DIGITS + "," + COLUMN_FAMILY + "," + DATA_TYPE + " FROM \"SYSTEM\".CATALOG WHERE " + TABLE_SCHEM + " = ? AND " + TABLE_NAME + " = ? AND " + COLUMN_NAME + " = ?"; try (Connection conn = DriverManager.getConnection(getUrl())) { PreparedStatement stmt = conn.prepareStatement(query); stmt.setString(1, schemaName); stmt.setString(2, tableName); stmt.setString(3, columnName); ResultSet rs = stmt.executeQuery(); assertTrue(rs.next()); if (expectedLenValue != null) { assertEquals(expectedLenValue.intValue(), rs.getInt(1)); } if (expectedScalaValue != null) { assertEquals(expectedScalaValue.intValue(), rs.getInt(2)); } if (dataType != null) { assertEquals(rs.getInt(4), dataType.getSqlType()); } assertFalse(rs.next()); } }