auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private static List<PartialSegmentMergeIOConfig> createMergeIOConfigs( int totalNumMergeTasks, Map<Pair<Interval, Integer>, List<PartitionLocation>> partitionToLocations ) { final int numMergeTasks = Math.min(totalNumMergeTasks, partitionToLocations.size()); LOG.info( "Number of merge tasks is set to [%d] based on totalNumMergeTasks[%d] and number of partitions[%d]", numMergeTasks, totalNumMergeTasks, partitionToLocations.size() ); final List<Pair<Interval, Integer>> partitions = new ArrayList<>(partitionToLocations.keySet()); Collections.shuffle(partitions, ThreadLocalRandom.current()); final int numPartitionsPerTask = (int) Math.round(partitions.size() / (double) numMergeTasks); final List<PartialSegmentMergeIOConfig> assignedPartitionLocations = new ArrayList<>(numMergeTasks); for (int i = 0; i < numMergeTasks - 1; i++) { final List<PartitionLocation> assingedToSameTask = partitions .subList(i * numPartitionsPerTask, (i + 1) * numPartitionsPerTask) .stream() .flatMap(intervalAndPartitionId -> partitionToLocations.get(intervalAndPartitionId).stream()) .collect(Collectors.toList()); assignedPartitionLocations.add(new PartialSegmentMergeIOConfig(assingedToSameTask)); } final List<PartitionLocation> assingedToSameTask = partitions .subList((numMergeTasks - 1) * numPartitionsPerTask, partitions.size()) .stream() .flatMap(intervalAndPartitionId -> partitionToLocations.get(intervalAndPartitionId).stream()) .collect(Collectors.toList()); assignedPartitionLocations.add(new PartialSegmentMergeIOConfig(assingedToSameTask)); return assignedPartitionLocations; }

Target:
private static List<PartialSegmentMergeIOConfig> createMergeIOConfigs( int totalNumMergeTasks, Map<Pair<Interval, Integer>, List<PartitionLocation>> partitionToLocations ) { final int numMergeTasks = Math.min(totalNumMergeTasks, partitionToLocations.size()); LOG.info( "Number of merge tasks is set to [%d] based on totalNumMergeTasks[%d] and number of partitions[%d]", numMergeTasks, totalNumMergeTasks, partitionToLocations.size() ); final List<Pair<Interval, Integer>> partitions = new ArrayList<>(partitionToLocations.keySet()); Collections.shuffle(partitions, ThreadLocalRandom.current()); final int numPartitionsPerTask = (int) Math.round(partitions.size() / (double) numMergeTasks); final List<PartialSegmentMergeIOConfig> assignedPartitionLocations = new ArrayList<>(numMergeTasks); for (int i = 0; i < numMergeTasks - 1; i++) { final List<PartitionLocation> assignedToSameTask = partitions .subList(i * numPartitionsPerTask, (i + 1) * numPartitionsPerTask) .stream() .flatMap(intervalAndPartitionId -> partitionToLocations.get(intervalAndPartitionId).stream()) .collect(Collectors.toList()); assignedPartitionLocations.add(new PartialSegmentMergeIOConfig(assignedToSameTask)); } final List<PartitionLocation> assignedToSameTask = partitions .subList((numMergeTasks - 1) * numPartitionsPerTask, partitions.size()) .stream() .flatMap(intervalAndPartitionId -> partitionToLocations.get(intervalAndPartitionId).stream()) .collect(Collectors.toList()); assignedPartitionLocations.add(new PartialSegmentMergeIOConfig(assignedToSameTask)); return assignedPartitionLocations; }
Source:
public void start(ConnectionFactoryConfiguration config, ClassLoader classLoader) throws PersistenceException { PooledConnectionFactoryConfiguration poolConfig; if (config instanceof PooledConnectionFactoryConfiguration) { poolConfig = (PooledConnectionFactoryConfiguration) config; } else { throw new PersistenceException("ConnectionFactoryConfiguration passed in must be an instance of " + "PooledConnectionFactoryConfiguration"); } try { String propsFile = poolConfig.propertyFile(); if (propsFile != null) { dataSource = AgroalDataSource.from(new AgroalPropertiesReader(PROPERTIES_PREFIX).readProperties(propsFile)); } else { Class<?> driverClass = Util.loadClass(poolConfig.driverClass(), null); Class<?> driverClass = Util.loadClass(poolConfig.driverClass(), null); String password = poolConfig.password() != null ? poolConfig.password() : ""; AgroalDataSourceConfigurationSupplier configuration = new AgroalDataSourceConfigurationSupplier() .connectionPoolConfiguration(cp -> cp .maxSize(10) .acquisitionTimeout(Duration.ofSeconds(30)) .connectionFactoryConfiguration(cf -> cf .jdbcUrl(poolConfig.connectionUrl()) .connectionProviderClass(driverClass) .jdbcTransactionIsolation(AgroalConnectionFactoryConfiguration.TransactionIsolation.UNDEFINED) .principal(new NamePrincipal(poolConfig.username())) .credential(new SimplePassword(password)) )); dataSource = AgroalDataSource.from(configuration); } } catch (Exception e) { throw new PersistenceException("Failed to create a AgroalDataSource", e); } }

Target:
public void start(ConnectionFactoryConfiguration config, ClassLoader classLoader) throws PersistenceException { PooledConnectionFactoryConfiguration poolConfig; if (config instanceof PooledConnectionFactoryConfiguration) { poolConfig = (PooledConnectionFactoryConfiguration) config; } else { throw new PersistenceException("ConnectionFactoryConfiguration passed in must be an instance of " + "PooledConnectionFactoryConfiguration"); } try { String propsFile = poolConfig.propertyFile(); if (propsFile != null) { dataSource = AgroalDataSource.from(new AgroalPropertiesReader(PROPERTIES_PREFIX).readProperties(propsFile)); } else { Class<?> driverClass = Util.loadClass(poolConfig.driverClass(), null); String password = poolConfig.password() != null ? poolConfig.password() : ""; AgroalDataSourceConfigurationSupplier configuration = new AgroalDataSourceConfigurationSupplier() .connectionPoolConfiguration(cp -> cp .maxSize(10) .acquisitionTimeout(Duration.ofSeconds(30)) .connectionFactoryConfiguration(cf -> cf .jdbcUrl(poolConfig.connectionUrl()) .connectionProviderClass(driverClass) .jdbcTransactionIsolation(AgroalConnectionFactoryConfiguration.TransactionIsolation.UNDEFINED) .principal(new NamePrincipal(poolConfig.username())) .credential(new SimplePassword(password)) )); dataSource = AgroalDataSource.from(configuration); } } catch (Exception e) { throw new PersistenceException("Failed to create a AgroalDataSource", e); } }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getAbstract() == null) ? 0 : getAbstract().hashCode()); result = prime * result + ((getAccessConstraints() == null) ? 0 : getAccessConstraints().hashCode()); result = prime * result + (citeCompliant ? 1231 : 1237); result = prime * result + (enabled ? 1231 : 1237); result = prime * result + ((exceptionFormats == null) ? 0 : exceptionFormats.hashCode()); result = prime * result + ((fees == null) ? 0 : fees.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((getKeywords() == null) ? 0 : getKeywords().hashCode()); result = prime * result + ((getMaintainer() == null) ? 0 : getMaintainer().hashCode()); result = prime * result + ((getMetadataLink() == null) ? 0 : getMetadataLink().hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((getOnlineResource() == null) ? 0 : getOnlineResource().hashCode()); result = prime * result + ((outputStrategy == null) ? 0 : outputStrategy.hashCode()); result = prime * result + ((getSchemaBaseURL() == null) ? 0 : getSchemaBaseURL().hashCode()); result = prime * result + ((getTitle() == null) ? 0 : getTitle().hashCode()); result = prime * result + (verbose ? 1231 : 1237); result = prime * result + ((versions == null) ? 0 : versions.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((abstrct == null) ? 0 : abstrct.hashCode()); result = prime * result + ((accessConstraints == null) ? 0 : accessConstraints .hashCode()); result = prime * result + (citeCompliant ? 1231 : 1237); result = prime * result + (enabled ? 1231 : 1237); result = prime * result + ((exceptionFormats == null) ? 0 : exceptionFormats.hashCode()); result = prime * result + ((fees == null) ? 0 : fees.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((keywords == null) ? 0 : keywords.hashCode()); result = prime * result + ((maintainer == null) ? 0 : maintainer.hashCode()); result = prime * result + ((metadataLink == null) ? 0 : metadataLink.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((onlineResource == null) ? 0 : onlineResource.hashCode()); result = prime * result + ((outputStrategy == null) ? 0 : outputStrategy.hashCode()); result = prime * result + ((schemaBaseURL == null) ? 0 : schemaBaseURL.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); result = prime * result + (verbose ? 1231 : 1237); result = prime * result + ((versions == null) ? 0 : versions.hashCode()); return result; }
Source:
public void onBackPressed() { if (pager.getCurrentItem() != 0) { pager.setCurrentItem(pager.getCurrentItem() - 1, true); } else { if(defaultKvStore.getBoolean("firstrun",true)){ finishAffinity(); } else{ finish(); } } }

Target:
public void onBackPressed() { if (pager.getCurrentItem() != 0) { pager.setCurrentItem(pager.getCurrentItem() - 1, true); } else { if (defaultKvStore.getBoolean("firstrun", true)) { finishAffinity(); } else { super.onBackPressed(); } } }
Source:
public void timestampIsCorrect() throws InterruptedException { assumeTrue(androidx.camera.testing.CameraUtil.hasCameraWithLensFacing(mLensFacing)); assumeTrue(ExtensionsManager.isExtensionAvailable(mEffectMode, mLensFacing)); enableExtension(mEffectMode, mLensFacing); ImageCapture imageCapture = new ImageCapture(mImageCaptureConfigBuilder.build()); PreviewConfig previewConfig = mPreviewConfigBuilder .build(); CaptureProcessor previewCaptureProcessor = previewConfig.getCaptureProcessor(null); assumeNotNull(previewCaptureProcessor); mPreviewConfigBuilder.setCaptureProcessor( new TimestampCaptureProcessor(previewCaptureProcessor, mTimestampListener)); Preview preview = new Preview(mPreviewConfigBuilder.build()); preview.setOnPreviewOutputUpdateListener(previewOutput -> { mProcessingHandler.post(() -> previewOutput.getSurfaceTexture() .attachToGLContext(GLUtil.getTexIdFromGLContext())); previewOutput.getSurfaceTexture().setOnFrameAvailableListener( mOnFrameAvailableListener, mProcessingHandler); mSurfaceTextureLatch.countDown(); } ); mMainHandler.post(() -> { CameraX.bindToLifecycle(mLifecycleOwner, preview, imageCapture); mLifecycleOwner.startAndResume(); }); assertTrue(mSurfaceTextureLatch.await(1000, TimeUnit.MILLISECONDS)); assertTrue(mInputTimestampsLatch.await(1000, TimeUnit.MILLISECONDS)); mOutputTimestampsLatch.await(3000, TimeUnit.MILLISECONDS); assertEquals(mInputTimestamps, mOutputTimestamps); }

Target:
public void timestampIsCorrect() throws InterruptedException { assumeTrue(androidx.camera.testing.CameraUtil.hasCameraWithLensFacing(mLensFacing)); assumeTrue(ExtensionsManager.isExtensionAvailable(mEffectMode, mLensFacing)); enableExtension(mEffectMode, mLensFacing); ImageCapture imageCapture = new ImageCapture(mImageCaptureConfigBuilder.build()); PreviewConfig previewConfig = mPreviewConfigBuilder .build(); CaptureProcessor previewCaptureProcessor = previewConfig.getCaptureProcessor(null); assumeNotNull(previewCaptureProcessor); mPreviewConfigBuilder.setCaptureProcessor( new TimestampCaptureProcessor(previewCaptureProcessor, mTimestampListener)); Preview preview = new Preview(mPreviewConfigBuilder.build()); preview.setOnPreviewOutputUpdateListener(previewOutput -> { mProcessingHandler.post(() -> previewOutput.getSurfaceTexture() .attachToGLContext(GLUtil.getTexIdFromGLContext())); previewOutput.getSurfaceTexture().setOnFrameAvailableListener( mOnFrameAvailableListener, mProcessingHandler); mSurfaceTextureLatch.countDown(); } ); mMainHandler.post(() -> { CameraX.bindToLifecycle(mLifecycleOwner, preview, imageCapture); mLifecycleOwner.startAndResume(); }); assertTrue(mSurfaceTextureLatch.await(1000, TimeUnit.MILLISECONDS)); assertTrue(mInputTimestampsLatch.await(1000, TimeUnit.MILLISECONDS)); assertTrue(mOutputTimestampsLatch.await(1000, TimeUnit.MILLISECONDS)); assertEquals(mInputTimestamps, mOutputTimestamps); }
Source:
public Map<Locator, MetricData> getEnumMetricDataForRangeForLocatorList(final List<Locator> locators, final Range range, final Granularity gran) { String columnFamily = CassandraModel.getColumnFamily(BluefloodEnumRollup.class, gran).getName(); if ( columnFamily == null ) { throw new IllegalArgumentException("invalid granularity: " + gran); } return getEnumMetricDataForRangeForLocatorList(locators, range, columnFamily); }

Target:
public Map<Locator, MetricData> getEnumMetricDataForRangeForLocatorList(final List<Locator> locators, final Range range, final Granularity gran) { String columnFamily = CassandraModel.getColumnFamily(BluefloodEnumRollup.class, gran).getName(); return getEnumMetricDataForRangeForLocatorList(locators, range, columnFamily); }
Source:
public boolean conforms() { final T inType = in().firstElement(); return inType instanceof Unsigned128BitType || inType instanceof UnsignedLongType || inType instanceof UnboundedIntegerType || inType instanceof LongType; }

Target:
public boolean conforms() { final Object inType = in().firstElement(); if (!(inType instanceof IntegerType)) return false; final T copy = in().firstElement().createVariable(); copy.setInteger(Long.MAX_VALUE); return copy.getIntegerLong() == Long.MAX_VALUE; }
Source:
protected void setPatternListener() { mPatternLockView.addPatternLockListener(new PatternLockViewListener() { @Override public void onStarted() { Log_OC.d(TAG, "Pattern Drawing Started"); } @Override public void onProgress(List<PatternLockView.Dot> list) { Log_OC.d(TAG, "Pattern Progress " + PatternLockUtils.patternToString(mPatternLockView, list)); } @Override public void onComplete(List<PatternLockView.Dot> list) { if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction())) { if (mCount == 0) { mPatternValue = PatternLockUtils.patternToString(mPatternLockView, list); mCount++; } else { mNewPatternValue = PatternLockUtils.patternToString(mPatternLockView, list); mCount = 0; } } else { mPatternValue = PatternLockUtils.patternToString(mPatternLockView, list); } Log_OC.d(TAG, "Pattern " + PatternLockUtils.patternToString(mPatternLockView, list)); processPattern(); } @Override public void onCleared() { Log_OC.d(TAG, "Pattern has been cleared"); } }); }

Target:
protected void setPatternListener() { mPatternLockView.addPatternLockListener(new PatternLockViewListener() { @Override public void onStarted() { Log_OC.d(TAG, "Pattern Drawing Started"); } @Override public void onProgress(List<PatternLockView.Dot> list) { Log_OC.d(TAG, "Pattern Progress " + PatternLockUtils.patternToString(mPatternLockView, list)); } @Override public void onComplete(List<PatternLockView.Dot> list) { if (ACTION_REQUEST_WITH_RESULT.equals(getIntent().getAction())) { if (mPatternValue == null || mPatternValue.length() <= 0) { mPatternValue = PatternLockUtils.patternToString(mPatternLockView, list); } else { mNewPatternValue = PatternLockUtils.patternToString(mPatternLockView, list); } } else { mPatternValue = PatternLockUtils.patternToString(mPatternLockView, list); } Log_OC.d(TAG, "Pattern " + PatternLockUtils.patternToString(mPatternLockView, list)); processPattern(); } @Override public void onCleared() { Log_OC.d(TAG, "Pattern has been cleared"); } }); }
Source:
public void frameSpecificValues() throws Throwable { SyncUtil.runToLocation("PrintHello"); MIStoppedEvent stoppedEvent = SyncUtil.step(StepType.STEP_OVER); Integer depth = SyncUtil.getStackDepth(stoppedEvent.getDMContext()); assertTrue((depth == Integer.valueOf(4))); String sp_name = resolveStackPointerName(); IFrameDMContext frame0 = SyncUtil.getStackFrame(stoppedEvent.getDMContext(), 0); IRegisterDMContext[] registers_f0 = getRegisters(frame0); MIRegisterDMC sp_reg_f0 = (MIRegisterDMC) findStackPointerRegister(sp_name, registers_f0); assertNotNull(sp_reg_f0); String sp_f0_str = getModelDataForRegisterDataValue(frame0, IFormattedValues.HEX_FORMAT, sp_reg_f0.getRegNo()); IFrameDMContext frame1 = SyncUtil.getStackFrame(stoppedEvent.getDMContext(), 1); IRegisterDMContext[] registers_f1 = getRegisters(frame1); MIRegisterDMC sp_reg_f1 = (MIRegisterDMC) findStackPointerRegister(sp_name, registers_f1); assertNotNull(sp_reg_f1); String sp_f1_str = getModelDataForRegisterDataValue(frame1, IFormattedValues.HEX_FORMAT, sp_reg_f1.getRegNo()); assertNotEquals("Stack pointers shall be different among frames", sp_f0_str, sp_f1_str); }

Target:
public void frameSpecificValues() throws Throwable { SyncUtil.runToLocation("PrintHello"); MIStoppedEvent stoppedEvent = SyncUtil.step(StepType.STEP_OVER); int depth = SyncUtil.getStackDepth(stoppedEvent.getDMContext()); assertEquals(4, depth); String sp_name = resolveStackPointerName(); assertNotNull(sp_name); IFrameDMContext frame0 = SyncUtil.getStackFrame(stoppedEvent.getDMContext(), 0); IRegisterDMContext[] registers_f0 = getRegisters(frame0); MIRegisterDMC sp_reg_f0 = (MIRegisterDMC) findStackPointerRegister(sp_name, registers_f0); assertNotNull(sp_reg_f0); String sp_f0_str = getModelDataForRegisterDataValue(frame0, IFormattedValues.HEX_FORMAT, sp_reg_f0.getRegNo()); IFrameDMContext frame1 = SyncUtil.getStackFrame(stoppedEvent.getDMContext(), 1); IRegisterDMContext[] registers_f1 = getRegisters(frame1); MIRegisterDMC sp_reg_f1 = (MIRegisterDMC) findStackPointerRegister(sp_name, registers_f1); assertNotNull(sp_reg_f1); String sp_f1_str = getModelDataForRegisterDataValue(frame1, IFormattedValues.HEX_FORMAT, sp_reg_f1.getRegNo()); assertNotEquals("Stack pointers shall be different among frames", sp_f0_str, sp_f1_str); }
Source:
private static List<SqlDecimal> decimalSequence(String start, String step, int items, int precision, int scale) { BigInteger decimalStep = new BigInteger(step); List<SqlDecimal> values = new ArrayList<>(); BigInteger nextValue = new BigInteger(start); for (int i = 0; i < items; i++) { SqlDecimal s = new SqlDecimal(nextValue, precision, scale); values.add(s); nextValue = nextValue.add(decimalStep); } return values; }

Target:
private static List<SqlDecimal> decimalSequence(String start, String step, int items, int precision, int scale) { BigInteger decimalStep = new BigInteger(step); List<SqlDecimal> values = new ArrayList<>(); BigInteger nextValue = new BigInteger(start); for (int i = 0; i < items; i++) { values.add(new SqlDecimal(nextValue, precision, scale)); nextValue = nextValue.add(decimalStep); } return values; }
Source:
public static String formatCaptions(List<UploadMediaDetail> uploadMediaDetails) { StringBuilder captionListString = new StringBuilder(); captionListString.append("{\\\"labels\\\":{"); UploadMediaDetail uploadMediaDetail = uploadMediaDetails.get(0); String individualDescription = "\\\""+uploadMediaDetail.getLanguageCode()+"\\\":{\\\"language\\\":\\\""+uploadMediaDetail.getLanguageCode()+"\\\",\\\"value\\\":\\\""+uploadMediaDetail.getLanguageCode()+"-"+uploadMediaDetail.getCaptionText()+"\\\"}"; captionListString.append(individualDescription); for (int i = 1;i<= uploadMediaDetails.size() - 1; i++) { uploadMediaDetail = uploadMediaDetails.get(i); individualDescription = ",\\\""+uploadMediaDetail.getLanguageCode()+"\\\":{\\\"language\\\":\\\""+uploadMediaDetail.getLanguageCode()+"\\\",\\\"value\\\":\\\""+uploadMediaDetail.getLanguageCode()+"-"+uploadMediaDetail.getCaptionText()+"\\\"}"; captionListString.append(individualDescription); } Timber.e(captionListString.toString()); return captionListString.toString(); }

Target:
public static HashMap<String, String> formatCaptions(List<UploadMediaDetail> uploadMediaDetails) { HashMap<String, String> caption = new HashMap<>(); for (UploadMediaDetail uploadMediaDetail : uploadMediaDetails) { caption.put(uploadMediaDetail.getLanguageCode(),uploadMediaDetail.getCaptionText()); } return caption; }
Source:
TokenCacheItem getRegularRefreshTokenCacheItem(final String resource, final String clientId, final String user) { CacheEvent cacheEvent = startCacheTelemetryRequest(EventStrings.TOKEN_TYPE_RT); final String cacheKey = CacheKey.createCacheKeyForRTEntry(mAuthority, resource, clientId, user); final TokenCacheItem item = mTokenCacheStore.getItem(cacheKey); if (item != null) { cacheEvent.setTokenTypeRT(true); } Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP); return item; }

Target:
TokenCacheItem getRegularRefreshTokenCacheItem(final String resource, final String clientId, final String user) { final CacheEvent cacheEvent = startCacheTelemetryRequest(EventStrings.TOKEN_TYPE_RT); final String cacheKey = CacheKey.createCacheKeyForRTEntry(mAuthority, resource, clientId, user); final TokenCacheItem item = mTokenCacheStore.getItem(cacheKey); if (item != null) { cacheEvent.setTokenTypeRT(true); } Telemetry.getInstance().stopEvent(mTelemetryRequestId, cacheEvent, EventStrings.TOKEN_CACHE_LOOKUP); return item; }
Source:
BasePackSubscribeConnection(PackTransport packTransport) { super(packTransport); closed = false; }

Target:
BasePackSubscribeConnection(PackTransport packTransport) { super(packTransport); }
Source:
public static MetadataTypeArgs parseArguments(CommandArgIterator argIter) { String typeName = null; Integer typeId = null; while (argIter.hasNextSubArg() && typeName == null && typeId == null) { String optName = argIter.nextArg("Expecting " + TYPE_NAME + " or " + TYPE_ID); switch (optName) { case TYPE_NAME: typeName = argIter.nextArg("type name"); break; case TYPE_ID: typeId = argIter.nextIntArg("typeId"); break; } } if (typeName == null && typeId == null) { throw new IllegalArgumentException("Type to remove is not specified. " + "Please add one of the options: --typeName <type_name> or --typeId <type_ID>"); } return new MetadataTypeArgs(typeName, typeId); }

Target:
public static MetadataTypeArgs parseArguments(CommandArgIterator argIter) { String typeName = null; Integer typeId = null; while (argIter.hasNextSubArg() && typeName == null && typeId == null) { String optName = argIter.nextArg("Expecting " + TYPE_NAME + " or " + TYPE_ID); switch (optName) { case TYPE_NAME: typeName = argIter.nextArg("type name"); break; case TYPE_ID: typeId = argIter.nextIntArg("typeId"); break; } } if (typeName == null && typeId == null) { throw new IllegalArgumentException("Type to remove is not specified. " + "Please add one of the options: --typeName <type_name> or --typeId <type_id>"); } return new MetadataTypeArgs(typeName, typeId); }
Source:
public Integer get(Cursor cursor) { return new SmartDarkening(mDarkenThreshold, super.get(cursor)).argb(); }

Target:
public Integer get(Cursor cursor) { return new SmoothLightnessCapped(mDarkenThreshold, super.get(cursor)).argb(); }
Source:
private void sendQueries() { long elapsedNs = System.nanoTime() - start; if (elapsedNs > timeoutNs) { LOG.warn("[{}] Schema agreement not reached after {}", logPrefix, NanoTime.format(elapsedNs)); result.complete(false); } CompletionStage<AdminResult> localQuery = query("SELECT schema_version FROM system.local WHERE key='local'"); CompletionStage<AdminResult> peersQuery = query("SELECT peer, rpc_address, schema_version FROM system.peers"); localQuery .thenCombine(peersQuery, this::extractSchemaVersions) .whenComplete(this::completeOrReschedule); }

Target:
private void sendQueries() { long elapsedNs = System.nanoTime() - start; if (elapsedNs > timeoutNs) { String message = String.format( "[%s] Schema agreement not reached after %s", logPrefix, NanoTime.format(elapsedNs)); if (warnOnFailure) { LOG.warn(message); } else { LOG.debug(message); } result.complete(false); } else { CompletionStage<AdminResult> localQuery = query("SELECT schema_version FROM system.local WHERE key='local'"); CompletionStage<AdminResult> peersQuery = query("SELECT peer, rpc_address, schema_version FROM system.peers"); localQuery .thenCombine(peersQuery, this::extractSchemaVersions) .whenComplete(this::completeOrReschedule); } }
Source:
protected void setEscalationRules(DocumentModel node, Map<String, Serializable>... rules) { node.setPropertyValue(GraphNode.PROP_ESCALATION_RULES, (Serializable) Arrays.asList(rules)); }

Target:
protected void setEscalationRules(DocumentModel node, Map<String, Serializable>... rules) { node.setPropertyValue(GraphNode.PROP_ESCALATION_RULES, (Serializable) List.of(rules)); }
Source:
public void removeItem(Column<T, ?> column) { ColumnContextMenuItem<T> item = items.get(column); if (item != null) { items.remove(column); container.remove(item); } }

Target:
public void removeItem(Column<T, ?> column) { ColumnContextMenuItem<T> removedItem = items.remove(column); if (removedItem != null) { container.remove(removedItem); } }
Source:
protected ClientProxyConnector initializeProxyConnector() throws Exception { ClientProxyConnector proxyConnector = getClientProxyConnector(); if (proxyConnector == null) { return null; } try { proxyConnector.sendClientProxyMetadata(this); return proxyConnector; } catch (Throwable t) { log.warn("initializeProxyConnector({}) failed ({}) to send proxy metadata: {}", this, t.getClass().getSimpleName(), t.getMessage()); if (log.isDebugEnabled()) { log.debug("initializeProxyConnector(" + this + ") proxy metadata send failure details", t); } if (t instanceof Exception) { throw (Exception) t; } else { throw new RuntimeSshException(t); } } }

Target:
protected void initializeProxyConnector() throws Exception { ClientProxyConnector proxyConnector = getClientProxyConnector(); boolean debugEnabled = log.isDebugEnabled(); if (proxyConnector == null) { if (debugEnabled) { log.debug("initializeProxyConnector({}) no proxy to initialize", this); } return; } try { if (debugEnabled) { log.debug("initializeProxyConnector({}) initialize proxy={}", this, proxyConnector); } proxyConnector.sendClientProxyMetadata(this); if (debugEnabled) { log.debug("initializeProxyConnector({}) proxy={} initialized", this, proxyConnector); } } catch (Throwable t) { log.warn("initializeProxyConnector({}) failed ({}) to send proxy metadata: {}", this, t.getClass().getSimpleName(), t.getMessage()); if (debugEnabled) { log.debug("initializeProxyConnector(" + this + ") proxy metadata send failure details", t); } if (t instanceof Exception) { throw (Exception) t; } else { throw new RuntimeSshException(t); } } }
Source:
public void typeAndWaitText(String text) { waitFormToOpen(); new WebDriverWait(seleniumWebDriver, TestTimeoutsConstants.LOAD_PAGE_TIMEOUT_SEC) .until(ExpectedConditions.visibilityOf(input)) .sendKeys(text); waitInputNameContains(text); }

Target:
public void typeAndWaitText(String text) { loadPageWait.until(visibilityOf(input)).sendKeys(text); waitInputNameContains(text); }
Source:
protected void addDescriptiveTextsAndExtensions(XmlStringBuilder xml) { for (Map.Entry<String, String> entry : descriptiveTexts.entrySet()) { String xmllang = entry.getKey(); String text = entry.getValue(); xml.halfOpenElement("text").xmlnsAttribute(textNamespace) .xmllangAttribute("".equals(xmllang) ? null : xmllang) .rightAngleBracket(); xml.escape(text); xml.closeElement("text"); } for (ExtensionElement packetExtension : extensions) { xml.append(packetExtension.toXML()); } }

Target:
protected void addDescriptiveTextsAndExtensions(XmlStringBuilder xml) { for (Map.Entry<String, String> entry : descriptiveTexts.entrySet()) { String xmllang = entry.getKey(); String text = entry.getValue(); xml.halfOpenElement("text").xmlnsAttribute(textNamespace) .optXmlLangAttribute(xmllang) .rightAngleBracket(); xml.escape(text); xml.closeElement("text"); } for (ExtensionElement packetExtension : extensions) { xml.append(packetExtension.toXML()); } }
Source:
public void visitExpressionStatement(ExpressionStatementTree tree) { ExpressionTree expression = tree.expression(); if (expression.is(USELESS_KINDS)) { uselessNodes.add(tree); } if (expression.is(Kind.REGULAR_STRING_LITERAL) && regularStringExceptionsPatterns().anyMatch(pattern -> !pattern.matcher(expression.toString()).find())) { uselessNodes.add(tree); } super.visitExpressionStatement(tree); }

Target:
public void visitExpressionStatement(ExpressionStatementTree tree) { ExpressionTree expression = tree.expression(); if (expression.is(USELESS_KINDS)) { uselessNodes.add(tree); } if (expression.is(Kind.REGULAR_STRING_LITERAL) && !STRING_LITERAL_EXCEPTION_PATTERN.matcher(((LiteralTree) expression).value()).find()) { uselessNodes.add(tree); } super.visitExpressionStatement(tree); }
Source:
public void unlock() { lockRefreshToken.ifPresent(lockService::unlock); }

Target:
public void unlock() { timeLock.unlock(ImmutableSet.of(lockToken)); }
Source:
public Object getConfigurationData(final HttpServletRequest request) { final Response configurationResponse = configurationResource.list(request); final Object entity = ResponseEntityView.class.cast(configurationResponse.getEntity()).getEntity(); return entity; }

Target:
public Map<String, Object> getConfigurationData(final HttpServletRequest request) { try { return configurationHelper.getConfigProperties(request); } catch (LanguageException e) { throw new LanguageRuntimeException(e); } }
Source:
private static QueryNode translateQuery(Map<String, Object> query, Map<String, Object> indexes, TranslatorState state) { ChildrenQueryNode root = null; List<Object> clauses = new ArrayList<Object>(); if (query.keySet().toArray()[0].equals(AND)) { clauses = (ArrayList<Object>) query.get(AND); root = new AndQueryNode(); } else if (query.keySet().toArray()[0].equals(OR)) { clauses = (ArrayList<Object>) query.get(OR); root = new OrQueryNode(); } List<Object> basicClauses = new ArrayList<Object>(); for (Object rawClause: clauses) { Map<String, Object> clause = (Map<String, Object>) rawClause; String field = (String) clause.keySet().toArray()[0]; if (!field.startsWith("$")) { basicClauses.add(rawClause); } } if (query.keySet().toArray()[0].equals(AND)) { String chosenIndex = chooseIndexForAndClause(basicClauses, indexes); if (chosenIndex == null || chosenIndex.isEmpty()) { state.atLeastOneIndexMissing = true; String msg = String.format("No single index contains all of %s; %s", basicClauses.toString(), "add index for these fields to query efficiently."); logger.log(Level.WARNING, msg); } else { state.atLeastOneIndexUsed = true; String select = selectStatementForAndClause(basicClauses, chosenIndex); if (select == null || select.isEmpty()) { String msg = String.format("Error generating SELECT clause for %s", basicClauses); logger.log(Level.SEVERE, msg); return null; } SqlQueryNode sqlNode = new SqlQueryNode(); sqlNode.sql = select; if (root != null) { root.children.add(sqlNode); } } } else if (query.keySet().toArray()[0].equals(OR)) { } return root; }

Target:
private static QueryNode translateQuery(Map<String, Object> query, Map<String, Object> indexes, TranslatorState state) { ChildrenQueryNode root = null; List<Object> clauses = new ArrayList<Object>(); if (query.get(AND) != null) { clauses = (ArrayList<Object>) query.get(AND); root = new AndQueryNode(); } else if (query.get(OR) != null) { clauses = (ArrayList<Object>) query.get(OR); root = new OrQueryNode(); } List<Object> basicClauses = new ArrayList<Object>(); for (Object rawClause: clauses) { Map<String, Object> clause = (Map<String, Object>) rawClause; String field = (String) clause.keySet().toArray()[0]; if (!field.startsWith("$")) { basicClauses.add(rawClause); } } if (query.get(AND) != null) { String chosenIndex = chooseIndexForAndClause(basicClauses, indexes); if (chosenIndex == null || chosenIndex.isEmpty()) { state.atLeastOneIndexMissing = true; String msg = String.format("No single index contains all of %s; %s", basicClauses.toString(), "add index for these fields to query efficiently."); logger.log(Level.WARNING, msg); } else { state.atLeastOneIndexUsed = true; SqlParts select = selectStatementForAndClause(basicClauses, chosenIndex); if (select == null) { String msg = String.format("Error generating SELECT clause for %s", basicClauses); logger.log(Level.SEVERE, msg); return null; } SqlQueryNode sqlNode = new SqlQueryNode(); sqlNode.sql = select; if (root != null) { root.children.add(sqlNode); } } } else if (query.get(OR) != null) { } return root; }
Source:
public static OffsetTime of(LocalTime localTime, ZoneOffset zoneOffset) { final OffsetTime result = OffsetTime.newBuilder() .setTime(localTime) .setOffset(zoneOffset) .build(); return result; }

Target:
public static OffsetTime of(LocalTime localTime, ZoneOffset zoneOffset) { checkNotNull(localTime); checkNotNull(zoneOffset); final OffsetTime result = OffsetTime.newBuilder() .setTime(localTime) .setOffset(zoneOffset) .build(); return result; }
Source:
private void _flushBloomFilter() { _logger.info("Flushing out bloom filter entries"); writeTagsBloomFilterToFile(); bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), bloomFilterExpectedNumberInsertions , bloomFilterErrorRate); bloomFilterScopeOnly = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), bloomFilterScopeOnlyExpectedNumberInsertions , bloomFilterScopeOnlyErrorRate); bloomFilterScopeAndMetricOnly = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), bloomFilterScopeAndMetricOnlyExpectedNumberInsertions , bloomFilterScopeAndMetricOnlyErrorRate); bloomFilterMetatags = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), bloomFilterMetatagsExpectedNumberInsertions , bloomFilterMetatagsErrorRate); randomNumber = rand.nextInt(); }

Target:
private void _flushBloomFilter() { _logger.info("Flushing out bloom filter entries"); writeTagsBloomFilterToFile(); bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), bloomFilterExpectedNumberInsertions , bloomFilterErrorRate); bloomFilterScopeOnly = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), bloomFilterScopeOnlyExpectedNumberInsertions , bloomFilterScopeOnlyErrorRate); bloomFilterScopeAndMetricOnly = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), bloomFilterScopeAndMetricOnlyExpectedNumberInsertions , bloomFilterScopeAndMetricOnlyErrorRate); bloomFilterMetatags = BloomFilter.create(Funnels.stringFunnel(Charset.defaultCharset()), bloomFilterMetatagsExpectedNumberInsertions , bloomFilterMetatagsErrorRate); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DistributionTrait other = (DistributionTrait) o; return type == other.type; }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DistributionTrait other = (DistributionTrait) o; return traitDef.equals(other.traitDef) && type == other.type; }
Source:
public void constructor_constructRepoPickerState_oneRepoSelected() { Set<String> existingRepositories = new HashSet<>(Arrays.asList("A/A", "B/B")); RepositoryPickerState state = new RepositoryPickerState(existingRepositories); assertEquals("A/A", state.getSelectedRepositoryId()); }

Target:
public void constructor_constructRepoPickerState_oneRepoSelected() { Set<String> existingRepositories = new HashSet<>(Arrays.asList("atom/atom", "HubTurbo/HubTurbo")); RepositoryPickerState state = new RepositoryPickerState(existingRepositories); assertEquals("atom/atom", state.getSelectedRepositoryId()); }
Source:
public boolean exists() { return isDeleted || resource.exists(); }

Target:
public boolean exists() { return !isDeleted && resource.exists(); }
Source:
public static void increaseClientCountToOne() { if (ACTIVE_CLIENT_COUNT.get() == 0) { ACTIVE_CLIENT_COUNT.set(1); } }

Target:
public static void increaseClientCountToOne() { ACTIVE_CLIENT_COUNT.compareAndSet(0,1); }
Source:
public List<String> tables() { final long TIMEOUT = 10000; synchronized (db) { long started = System.currentTimeMillis(); long now = started; while (tables == null && now - started < TIMEOUT) { try { db.wait(TIMEOUT - (now - started)); } catch (InterruptedException e) { } now = System.currentTimeMillis(); } if (tables == null) { throw new CopycatException("Tables could not be updated quickly enough."); } return tables; } }

Target:
public List<String> tables() { final long TIMEOUT = 10000L; synchronized (db) { long started = System.currentTimeMillis(); long now = started; while (tables == null && now - started < TIMEOUT) { try { db.wait(TIMEOUT - (now - started)); } catch (InterruptedException e) { } now = System.currentTimeMillis(); } if (tables == null) { throw new CopycatException("Tables could not be updated quickly enough."); } return tables; } }
Source:
private void fillEventTypeAndTargetFromConfig( Set<EventTypeAndTarget> set, List<String> stringList) { for (String item : stringList) { if (item.trim().equals("")) { continue; } String[] split = item.split("-"); if (split.length != 2) { throw new IllegalArgumentException("Invalid include/exclude rule: " + item + "Each filter auditing" + "include/exclude must be in format TYPE-TARGET. For example MODIFIED-CONSUMER."); } try { Type type = Enum.valueOf(Type.class, split[0].trim()); Target target = Enum.valueOf(Target.class, split[1].trim()); set.add(new EventTypeAndTarget(type, target)); } catch (Exception ex) { throw new IllegalArgumentException("Invalid filtering touple: " + item + " . Please use only enum values of Type and Target enums, e.g. MODIFIED-CONSUMER"); } } }

Target:
private void fillEventTypeAndTargetFromConfig( Set<EventTypeAndTarget> set, List<String> stringList) { for (String item : stringList) { if (item.trim().equals("")) { continue; } String[] split = item.split("-"); if (split.length != 2) { throw new IllegalArgumentException("Invalid include/exclude rule: " + item + "Each filter auditing" + "include/exclude must be in format TYPE-TARGET. For example MODIFIED-CONSUMER."); } try { Type type = Enum.valueOf(Type.class, split[0].trim()); Target target = Enum.valueOf(Target.class, split[1].trim()); set.add(new EventTypeAndTarget(type, target)); } catch (Exception ex) { throw new IllegalArgumentException("Invalid filtering tuple: " + item + " . Please use only enum values of Type and Target enums, e.g. MODIFIED-CONSUMER"); } } }
Source:
public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(TypecastParenPadCheck.class); final String[] expected = { "89:14: " + getCheckMessage(MSG_WS_FOLLOWED, "("), "89:21: " + getCheckMessage(MSG_WS_PRECEDED, ")"), }; verify(checkConfig, getPath("InputWhitespace[TypecastParenPad].java"), expected); }

Target:
public void testDefault() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(TypecastParenPadCheck.class); final String[] expected = { "89:14: " + getCheckMessage(MSG_WS_FOLLOWED, "("), "89:21: " + getCheckMessage(MSG_WS_PRECEDED, ")"), }; verify(checkConfig, getPath("InputTypecastParenPadWhitespace.java"), expected); }
Source:
public LeasableRefreshLockResponse refresh(Set<LockToken> tokens) { NanoTime startTime = NanoTime.now(); Set<LockToken> refreshedTokens = heldLocks.refresh(tokens); return LeasableRefreshLockResponse.of( refreshedTokens, leaseWithStart(startTime)); }

Target:
public RefreshLockResponseV2 refresh(Set<LockToken> tokens) { Leased<Set<LockToken>> refreshedTokens = heldLocks.refresh(tokens); return RefreshLockResponseV2.of( refreshedTokens.value(), refreshedTokens.lease()); }
Source:
public List<String> tokenize(String input) { try (TokenStream ts = this.tokenStream("", input)) { ts.reset(); List<String> words = new ArrayList<>(); CharTermAttribute charTermAttribute = ts.getAttribute(CharTermAttribute.class); while (ts.incrementToken()) { words.add(charTermAttribute.toString()); } return Collections.unmodifiableList(words); } catch (IOException e) { throw new Error(e); } }

Target:
public final List<String> tokenize(String input) { try (TokenStream ts = this.tokenStream("", input)) { ts.reset(); ImmutableList.Builder<String> builder = ImmutableList.builder(); CharTermAttribute charTermAttribute = ts.getAttribute(CharTermAttribute.class); while (ts.incrementToken()) { builder.add(charTermAttribute.toString()); } return builder.build(); } catch (IOException e) { throw new Error(e); } }
Source:
void trivialMatchers() { assertMatch(any(), 42); assertMatch(any(), "John Doe"); assertMatch(typeOf(Integer.class), 42); assertMatch(typeOf(Number.class), 42); assertNoMatch(typeOf(Integer.class), "John Doe"); }

Target:
public void trivialMatchers() { assertMatch(any(), 42); assertMatch(any(), "John Doe"); assertMatch(typeOf(Integer.class), 42); assertMatch(typeOf(Number.class), 42); assertNoMatch(typeOf(Integer.class), "John Doe"); }
Source:
public Iterator<Event> getEvents() { final File[] fileArray = bufferDir.listFiles(); if (fileArray == null) { return new ArrayList<Event>(0).iterator(); } final Iterator<File> files = Arrays.asList(fileArray).iterator(); return new Iterator<Event>() { private Event next = getNextEvent(files); @Override public boolean hasNext() { return next != null; } @Override public Event next() { Event toReturn = next; next = getNextEvent(files); return toReturn; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }

Target:
public Iterator<Event> getEvents() { final File[] fileArray = bufferDir.listFiles(); if (fileArray == null) { return Collections.emptyIterator(); } final Iterator<File> files = Arrays.asList(fileArray).iterator(); return new Iterator<Event>() { private Event next = getNextEvent(files); @Override public boolean hasNext() { return next != null; } @Override public Event next() { Event toReturn = next; next = getNextEvent(files); return toReturn; } @Override public void remove() { throw new UnsupportedOperationException(); } }; }
Source:
public VDS getRandomUpServer(Guid clusterId) { List<VDS> servers = getAllUpServers(clusterId); if (servers == null || servers.isEmpty()) { return null; } return servers.get(new Random().nextInt(servers.size())); }

Target:
public VDS getRandomUpServer(Guid clusterId) { List<VDS> servers = getAllUpServers(clusterId); if (CollectionUtils.isEmpty(servers)) { return null; } return servers.get(new Random().nextInt(servers.size())); }
Source:
public Optional<SystemTable> getSystemTable(ConnectorSession session, SchemaTableName tableName) { if (partitionsTableHandler.matches(tableName)) { return getPartitionsSystemTable(session, tableName, partitionsTableHandler.getSourceTableName(tableName)); } else if (propertiesTableHandler.matches(tableName)) { return getPropertiesSystemTable(session, tableName, propertiesTableHandler.getSourceTableName(tableName)); } return Optional.empty(); }

Target:
public Optional<SystemTable> getSystemTable(ConnectorSession session, SchemaTableName tableName) { if (PARTITIONS_TABLE_HANDLER.matches(tableName)) { return getPartitionsSystemTable(session, tableName, PARTITIONS_TABLE_HANDLER.getSourceTableName(tableName)); } if (PROPERTIES_TABLE_HANDLER.matches(tableName)) { return getPropertiesSystemTable(session, tableName, PROPERTIES_TABLE_HANDLER.getSourceTableName(tableName)); } return Optional.empty(); }
Source:
public JAIEXTInfoImpl() { if(jaiOperations == null ){ jaiOperations = JAI_OPS; } if(jaiExtOperations == null ){ jaiExtOperations = JAIEXT_OPS; } List<OperationItem> jaiextOps = JAIExt.getJAIEXTOperations(); for(OperationItem item : jaiextOps){ String name = item.getName(); if (name.equalsIgnoreCase("algebric") || name.equalsIgnoreCase("operationConst") || name.equalsIgnoreCase("Stats")) { jaiExtOperations.add(name); }else if(JAIExt.isJAIAPI(name)){ jaiExtOperations.add(name); } } }

Target:
public JAIEXTInfoImpl() { if (jaiOperations == null) { jaiOperations = JAI_OPS; } if (jaiExtOperations == null) { jaiExtOperations = JAIEXT_OPS; } populateOperations(jaiExtOperations); }
Source:
private void removeDRSnapshots() { for (Guid vmId: getParameters().getSnapshotIdVmIds().keySet()) { RemoveSnapshotParameters removeSnapshotParameters = new RemoveSnapshotParameters(getParameters().getSnapshotIdVmIds().get(vmId), vmId); removeSnapshotParameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); removeSnapshotParameters.setParentCommand(getActionType()); removeSnapshotParameters.setParentParameters(getParameters()); removeSnapshotParameters.setNeedsLocking(false); runInternalAction(VdcActionType.RemoveSnapshot, removeSnapshotParameters, ExecutionHandler.createInternalJobContext(getContext())); } }

Target:
private void removeDRSnapshots() { for (Map.Entry<Guid, Guid> entry : getParameters().getVmIdSnapshotIds().entrySet()) { RemoveSnapshotParameters removeSnapshotParameters = new RemoveSnapshotParameters(entry.getValue(), entry.getKey()); removeSnapshotParameters.setEndProcedure(EndProcedure.COMMAND_MANAGED); removeSnapshotParameters.setParentCommand(getActionType()); removeSnapshotParameters.setParentParameters(getParameters()); removeSnapshotParameters.setNeedsLocking(false); runInternalAction(VdcActionType.RemoveSnapshot, removeSnapshotParameters, ExecutionHandler.createInternalJobContext(getContext())); } }
Source:
public long getNumUserSessions(DbUser user) { return sessionInfoMap.keySet() .stream() .filter(sessionId -> getUser(sessionId, false).getId().equals(user.getId())) .filter(sessionId -> getSessionValid(sessionId, false)) .count(); }

Target:
public long getNumUserSessions(DbUser user) { return sessionInfoMap.entrySet() .stream() .filter(map -> ((DbUser) map.getValue().contentOfSession.get(USER_PARAMETER_NAME)).getId() .equals(user.getId()) && getSessionValid((String) map.getValue().contentOfSession.get(ENGINE_SESSION_ID), false)) .count(); }
Source:
protected LDAPConnectionFactory createLdapConnectionFactory(String url, Boolean startTls) throws LdapException { boolean useSsl = url.startsWith("ldaps"); boolean useTls = !url.startsWith("ldaps") && startTls; Options lo = Options.defaultOptions(); try { if (useSsl || useTls) { LOGGER.trace("Setting up secure LDAP connection."); initializeSslContext(); lo.set(LDAPConnectionFactory.SSL_CONTEXT, getSslContext()); } else { LOGGER.trace("Setting up insecure LDAP connection."); } } catch (GeneralSecurityException e) { LOGGER.info("Error encountered while configuring SSL. Secure connection will fail.", e); } lo.set(LDAPConnectionFactory.HEARTBEAT_TIMEOUT, new Duration(30L, TimeUnit.SECONDS)); lo.set(LDAPConnectionFactory.HEARTBEAT_INTERVAL, new Duration(60L, TimeUnit.SECONDS)); lo.set(LDAPConnectionFactory.CONNECT_TIMEOUT, new Duration(30L, TimeUnit.SECONDS)); lo.set(LDAPConnectionFactory.SSL_USE_STARTTLS, useTls); lo.set( LDAPConnectionFactory.SSL_ENABLED_CIPHER_SUITES, Arrays.asList(System.getProperty("https.cipherSuites", "").split(","))); lo.set( LDAPConnectionFactory.SSL_ENABLED_PROTOCOLS, Arrays.asList(System.getProperty("https.protocols", "").split(","))); lo.set( LDAPConnectionFactory.TRANSPORT_PROVIDER_CLASS_LOADER, SslLdapLoginModule.class.getClassLoader()); String host = url.substring(url.indexOf("://") + 3, url.lastIndexOf(':')); Integer port = useSsl ? 636 : 389; try { port = Integer.valueOf(url.substring(url.lastIndexOf(':') + 1)); } catch (NumberFormatException ignore) { } auditRemoteConnection(host); return new LDAPConnectionFactory(host, port, lo); }

Target:
protected LDAPConnectionFactory createLdapConnectionFactory(String url, Boolean startTls) { boolean useSsl = url.startsWith("ldaps"); boolean useTls = !url.startsWith("ldaps") && startTls; Options lo = Options.defaultOptions(); try { if (useSsl || useTls) { LOGGER.trace("Setting up secure LDAP connection."); initializeSslContext(); lo.set(LDAPConnectionFactory.SSL_CONTEXT, getSslContext()); } else { LOGGER.trace("Setting up insecure LDAP connection."); } } catch (GeneralSecurityException e) { LOGGER.info("Error encountered while configuring SSL. Secure connection will fail.", e); } lo.set(LDAPConnectionFactory.HEARTBEAT_TIMEOUT, new Duration(30L, TimeUnit.SECONDS)); lo.set(LDAPConnectionFactory.HEARTBEAT_INTERVAL, new Duration(60L, TimeUnit.SECONDS)); lo.set(LDAPConnectionFactory.CONNECT_TIMEOUT, new Duration(30L, TimeUnit.SECONDS)); lo.set(LDAPConnectionFactory.SSL_USE_STARTTLS, useTls); String cipherSuites = System.getProperty(SecurityConstants.HTTPS_CIPHER_SUITES); if (cipherSuites != null) { lo.set( LDAPConnectionFactory.SSL_ENABLED_CIPHER_SUITES, Arrays.asList(cipherSuites.split(","))); } String protocols = System.getProperty(HTTPS_PROTOCOLS); if (protocols != null) { lo.set(LDAPConnectionFactory.SSL_ENABLED_PROTOCOLS, Arrays.asList(protocols.split(","))); } lo.set( LDAPConnectionFactory.TRANSPORT_PROVIDER_CLASS_LOADER, SslLdapLoginModule.class.getClassLoader()); LDAPUrl parsedUrl = LDAPUrl.valueOf(url); String host = parsedUrl.getHost(); Integer port = parsedUrl.getPort(); auditRemoteConnection(host); return new LDAPConnectionFactory(host, port, lo); }