auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public DbHelper(Context context, boolean persistent) { super(context, persistent ? DATABASE_NAME : null, null, DATABASE_VERSION); SharedPreferences pref = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); boolean encrypt = pref.getBoolean(Advanced.ENCRYPT_SENSOR_DATA, false); if (encrypt) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String imei = telephonyManager.getDeviceId(); setPassphrase(imei); } SQLiteDatabase.loadLibs(context); if (persistent && encrypt) { try { getWritableDatabase(passphrase); } catch (SQLiteException e) { Log.v(TAG, "Encrypting old database with passphrase "+passphrase); File plain = context.getDatabasePath(DATABASE_NAME); File encrypted = context.getDatabasePath("tmp.db"); SQLiteDatabase migrate_db = SQLiteDatabase.openOrCreateDatabase(plain, "", null); migrate_db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s'", encrypted.getAbsolutePath(), passphrase)); migrate_db.rawExecSQL("SELECT sqlcipher_export('encrypted');"); migrate_db.execSQL("DETACH DATABASE encrypted;"); migrate_db.close(); encrypted.renameTo(new File(plain.getAbsolutePath())); } } }

Target:
public DbHelper(Context context, boolean persistent) { super(context, persistent ? DATABASE_NAME : null, null, DATABASE_VERSION); if (null == sMainPrefs) { sMainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE); } boolean encrypt = sMainPrefs.getBoolean(Advanced.ENCRYPT_DATABASE, false); if (encrypt) { TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); String imei = telephonyManager.getDeviceId(); setPassphrase(imei); } SQLiteDatabase.loadLibs(context); if (persistent && encrypt) { try { getWritableDatabase(passphrase); } catch (SQLiteException e) { Log.v(TAG, "Trying to encrypte old plain database"); File plain = context.getDatabasePath(DATABASE_NAME); File encrypted = context.getDatabasePath("tmp.db"); SQLiteDatabase migrate_db = SQLiteDatabase.openOrCreateDatabase(plain, "", null); migrate_db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted KEY '%s'", encrypted.getAbsolutePath(), passphrase)); migrate_db.rawExecSQL("SELECT sqlcipher_export('encrypted');"); migrate_db.execSQL("DETACH DATABASE encrypted;"); migrate_db.close(); encrypted.renameTo(new File(plain.getAbsolutePath())); } } }
Source:
private Properties getDeploymentProperties(String metadataPath) { Map<String, String> deploymentProperties = new HashMap<String, String>(); try { String moduleDeploymentsPath = metadataPath.substring(0, metadataPath.lastIndexOf("/")); deploymentProperties = mapBytesUtility.toMap(zkConnection.getClient().getData().forPath( moduleDeploymentsPath)); } catch (Exception e) { ZooKeeperUtils.wrapAndThrowIgnoring(e); } return MapUtils.toProperties(deploymentProperties); }

Target:
private Properties getDeploymentProperties(String metadataPath) { Map<String, String> deploymentProperties = new HashMap<String, String>(); try { String moduleDeploymentsPath = metadataPath.substring(0, metadataPath.lastIndexOf("/")); deploymentProperties = mapBytesUtility.toMap(zkConnection.getClient().getData().forPath( moduleDeploymentsPath)); } catch (Exception e) { ZooKeeperUtils.wrapAndThrowIgnoring(e, NoNodeException.class); } return MapUtils.toProperties(deploymentProperties); }
Source:
public void testCheckoutOursWhenNoBase() throws Exception { String file = "added.txt"; git.checkout().setCreateBranch(true).setName("side") .setStartPoint(initialCommit).call(); writeTrashFile(file, "Added on side"); git.add().addFilepattern(file).call(); RevCommit side = git.commit().setMessage("Commit on side").call(); git.checkout().setName("master").call(); writeTrashFile(file, "Added on master"); git.add().addFilepattern(file).call(); git.commit().setMessage("Commit on master").call(); git.merge().include(side).call(); assertEquals(RepositoryState.MERGING, db.getRepositoryState()); DirCache cache = DirCache.read(db.getIndexFile(), db.getFS()); assertEquals("Expected add/add file to not have base stage", DirCacheEntry.STAGE_2, cache.getEntry(file).getStage()); git.checkout().setStage(Stage.OURS).addPath(file).call(); assertEquals("Added on master", read(file)); cache = DirCache.read(db.getIndexFile(), db.getFS()); assertEquals("Expected conflict stages to still exist after checkout", DirCacheEntry.STAGE_2, cache.getEntry(file).getStage()); }

Target:
public void testCheckoutOursWhenNoBase() throws Exception { String file = "added.txt"; git.checkout().setCreateBranch(true).setName("side") .setStartPoint(initialCommit).call(); writeTrashFile(file, "Added on side"); git.add().addFilepattern(file).call(); RevCommit side = git.commit().setMessage("Commit on side").call(); git.checkout().setName("master").call(); writeTrashFile(file, "Added on master"); git.add().addFilepattern(file).call(); git.commit().setMessage("Commit on master").call(); git.merge().include(side).call(); assertEquals(RepositoryState.MERGING, db.getRepositoryState()); DirCache cache = DirCache.read(db.getIndexFile(), db.getFS()); assertEquals("Expected add/add file to not have base stage", DirCacheEntry.STAGE_2, cache.getEntry(file).getStage()); assertTrue(read(file).startsWith("<<<<<<< HEAD")); git.checkout().setStage(Stage.OURS).addPath(file).call(); assertEquals("Added on master", read(file)); cache = DirCache.read(db.getIndexFile(), db.getFS()); assertEquals("Expected conflict stages to still exist after checkout", DirCacheEntry.STAGE_2, cache.getEntry(file).getStage()); }
Source:
public void star() throws IOException { this.entry.uri() .path(RtGist.PATH_ELEMENT_STAR).back().method("PUT") .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_NO_CONTENT); }

Target:
public void star() throws IOException { this.request.method("PUT") .fetch().as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_NO_CONTENT); }
Source:
public void registerPostCreationEventConsumer(CircuitBreakerRegistry circuitBreakerRegistry, EventConsumerRegistry<CircuitBreakerEvent> eventConsumerRegistry) { eventConsumerRegister = new EventConsumerRegister(eventConsumerRegistry); circuitBreakerRegistry.registerPostCreationConsumer( (circuitBreaker, config) -> eventConsumerRegister.registerEventConsumer(circuitBreaker, config)); }

Target:
public void registerPostCreationEventConsumer(CircuitBreakerRegistry circuitBreakerRegistry, EventConsumerRegistry<CircuitBreakerEvent> eventConsumerRegistry) { final EventConsumerRegister eventConsumerRegister = new EventConsumerRegister(eventConsumerRegistry); circuitBreakerRegistry.registerPostCreationConsumer(eventConsumerRegister::registerEventConsumer); }
Source:
private ArrayList<String> split(String str) { if (str == null || str.isEmpty()) { return null; } return new ArrayList<String>(Arrays.asList(str.split(SEPARATOR))); }

Target:
private ArrayList<String> split(String str) { if (StringHelper.isNullOrEmpty(str)) { return null; } return new ArrayList<String>(Arrays.asList(str.split(SEPARATOR))); }
Source:
public GroupDto(Group group) { this.id = group.getId(); this.name = group.getName(); this.users = UserDto.convertToUserDtoList(group.getUsers(), UserDto.BY_NAME_COMPARATOR, DISPLAY_USER_LIMIT); }

Target:
public GroupDto(Group group) { this.id = group.getId(); this.name = group.getName(); }
Source:
public Response getExtensions() { LOG.error("Enumerate is not supported on Server.Please run your operation on prism "); throw FalconWebException.newAPIException("Enumerate is not supported on Server.Please run your operation " + "on prism."); }

Target:
public Response getExtensions() { LOG.error("Enumerate is not supported on Server.Please run your operation on Prism "); throw FalconWebException.newAPIException("Enumerate is not supported on Server. Please run your operation " + "on Prism."); }
Source:
private Iterable<String> quote(List<String> command) { return command.stream().map((String s) -> "\"" + s + "\"").collect(Collectors.toList()); }

Target:
private Iterable<String> quote(List<String> command) { return command.stream() .map((String s) -> "\"" + s + "\"") .collect(toImmutableList()); }
Source:
public void run() { try { Log.d(MSG_SERVER_TAG, "Start receiving the msg"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(1024); byte[] buffer = new byte[1024]; int bytesRead; InputStream inputStream = hostThreadSocket.getInputStream(); while ((bytesRead = inputStream.read(buffer)) != -1){ byteArrayOutputStream.write(buffer, 0, bytesRead); msgRec += byteArrayOutputStream.toString("UTF-8"); } Log.d(MSG_SERVER_TAG, "Got msg from client " + msgRec); }catch (IOException e) { e.printStackTrace(); } }

Target:
public void run() { try { Log.d(MSG_SERVER_TAG, "Start receiving the msg"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(MAX_MSG_SIZE); byte[] buffer = new byte[MAX_MSG_SIZE]; int bytesRead; InputStream inputStream = hostThreadSocket.getInputStream(); msgRec = new StringBuffer(); bytesRead = inputStream.read(buffer); byteArrayOutputStream.write(buffer, 0, bytesRead); msgRec.append(byteArrayOutputStream.toString("UTF-8")); inputStream.close(); Log.d(MSG_SERVER_TAG, "Got msg from client " + msgRec); if(mMsgRecListenerForThread != null){ mMsgRecListenerForThread.onMessageReceived(msgRec.toString()); }else{ Log.e(MSG_SERVER_TAG, "Message Receiving Listener is not set"); } }catch (IOException e) { e.printStackTrace(); } }
Source:
public void addController(final ServiceController<?> controller) { if (controller == null) return; final ServiceControllerImpl<?> serviceController = (ServiceControllerImpl<?>) controller; synchronized (controllersLock) { while (cleanupInProgress) { try { controllersLock.wait(); } catch (final InterruptedException ignored) } if (controllers.add(serviceController)) { serviceController.addMonitor(this); } } }

Target:
public void addController(final ServiceController<?> controller) { if (controller == null) return; final ServiceControllerImpl<?> serviceController = (ServiceControllerImpl<?>) controller; synchronized (controllersLock) { awaitCleanupCompletion(); if (controllers.add(serviceController)) { serviceController.addMonitor(this); } } }
Source:
private static void validateSymlinkPath(Location location, String attrName, PathFragment symlinkPath, FileTypeSet filetypes, StringBuilder errorsBuilder) throws EvalException { String extensionErrorMessage = "does not have any of the allowed extensions"; if (symlinkPath.isEmpty() || symlinkPath.isAbsolute() || symlinkPath.containsUplevelReferences()) { throw new EvalException( location, String.format("%s must be a relative file path. Got '%s'", attrName, symlinkPath)); } if (!filetypes.matches(symlinkPath.getBaseName())) { errorsBuilder.append( String.format( "'%s' %s %s", symlinkPath, extensionErrorMessage, filetypes)); errorsBuilder.append(LINE_SEPARATOR.value()); } }

Target:
private static void validateSymlinkPath(Location location, String attrName, PathFragment symlinkPath, FileTypeSet filetypes, StringBuilder errorsBuilder) throws EvalException { if (symlinkPath.isEmpty() || symlinkPath.isAbsolute() || symlinkPath.containsUplevelReferences()) { throw new EvalException( location, String.format("%s must be a relative file path. Got '%s'", attrName, symlinkPath)); } if (!filetypes.matches(symlinkPath.getBaseName())) { errorsBuilder.append( String.format( "'%s' %s %s", symlinkPath, "does not have any of the allowed extensions", filetypes)); errorsBuilder.append(LINE_SEPARATOR.value()); } }
Source:
Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler, Downloader downloader, Cache cache) { DispatcherThread thread = new DispatcherThread(); thread.start(); this.context = context; this.service = service; this.hunterMap = new LinkedHashMap<String, BitmapHunter>(); this.handler = new DispatcherHandler(thread.getLooper()); this.downloader = downloader; this.mainThreadHandler = mainThreadHandler; this.cache = cache; this.batch = new ArrayList<BitmapHunter>(); this.airplaneMode = Utils.isAirplaneModeOn(this.context); NetworkBroadcastReceiver receiver = new NetworkBroadcastReceiver(this.context); receiver.register(); }

Target:
Dispatcher(Context context, ExecutorService service, Handler mainThreadHandler, Downloader downloader, Cache cache) { DispatcherThread thread = new DispatcherThread(); thread.start(); this.context = context; this.service = service; this.hunterMap = new LinkedHashMap<String, BitmapHunter>(); this.handler = new DispatcherHandler(thread.getLooper()); this.downloader = downloader; this.mainThreadHandler = mainThreadHandler; this.cache = cache; this.batch = new ArrayList<BitmapHunter>(4); this.airplaneMode = Utils.isAirplaneModeOn(this.context); NetworkBroadcastReceiver receiver = new NetworkBroadcastReceiver(this.context); receiver.register(); }
Source:
public void givenNestedObjectsDifferentArrayOrder_whenCompared_thenNotEqual() { JsonParser parser = new JsonParser(); String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}"; String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"eggs\", \"banana\"]}}}"; JsonElement json1 = parser.parse(string1); JsonElement json2 = parser.parse(string2); Assert.assertTrue(json1.isJsonObject()); Assert.assertNotEquals(json1, json2); }

Target:
public void givenNestedObjectsDifferentArrayOrder_whenCompared_thenNotEqual() { JsonParser parser = new JsonParser(); String string1 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"banana\", \"eggs\"]}}}"; String string2 = "{\"customer\": {\"id\": \"44521\",\"fullName\": \"Emily Jenkins\", \"age\": 27, \"consumption_info\" : {\"last_buy\": \"2012-04-23\", \"prouducts\": [\"eggs\", \"banana\"]}}}"; JsonElement json1 = parser.parse(string1); JsonElement json2 = parser.parse(string2); assertNotEquals(json1, json2); }
Source:
public static String formatResponse(GsonProvider gsonProvider, ElasticsearchResponse response) { if ( response == null ) { return null; } JsonObject body = response.getBody(); StringBuilder sb = new StringBuilder( 128 ); sb.append( "Status: " ).append( response.getStatusCode() ).append( " " ).append( response.getStatusMessage() ); sb.append( "\nError message: " ).append( propertyAsString( body, "error" ) ); sb.append( "\nCluster name: " ).append( propertyAsString( body, "cluster_name" ) ); sb.append( "\nCluster status: " ).append( propertyAsString( body, "status" ) ); sb.append( "\n\n" ); JsonElement items = property( body, "items" ); if ( items != null && items.isJsonArray() ) { for ( JsonElement item : items.getAsJsonArray() ) { for ( Map.Entry<String, JsonElement> entry : item.getAsJsonObject().entrySet() ) { sb.append( "Operation: " ).append( entry.getKey() ); JsonElement value = entry.getValue(); sb.append( "\n Index: " ).append( propertyAsString( value, "_index" ) ); sb.append( "\n Type: " ).append( propertyAsString( value, "_type" ) ); sb.append( "\n Id: " ).append( propertyAsString( value, "_id" ) ); sb.append( "\n Status: " ).append( propertyAsString( value, "status" ) ); sb.append( "\n Error: " ).append( propertyAsString( value, "error" ) ) .append( "\n" ); } } } return sb.toString(); }

Target:
public static String formatResponse(GsonProvider gsonProvider, ElasticsearchResponse response) { if ( response == null ) { return null; } JsonObject body = response.getBody(); StringBuilder sb = new StringBuilder( 180 ); sb.append( "Status: " ).append( response.getStatusCode() ).append( " " ).append( response.getStatusMessage() ); sb.append( "\nError message: " ).append( propertyAsString( body, "error" ) ); sb.append( "\nCluster name: " ).append( propertyAsString( body, "cluster_name" ) ); sb.append( "\nCluster status: " ).append( propertyAsString( body, "status" ) ); sb.append( "\n\n" ); JsonElement items = property( body, "items" ); if ( items != null && items.isJsonArray() ) { for ( JsonElement item : items.getAsJsonArray() ) { for ( Map.Entry<String, JsonElement> entry : item.getAsJsonObject().entrySet() ) { sb.append( "Operation: " ).append( entry.getKey() ); JsonElement value = entry.getValue(); sb.append( "\n Index: " ).append( propertyAsString( value, "_index" ) ); sb.append( "\n Type: " ).append( propertyAsString( value, "_type" ) ); sb.append( "\n Id: " ).append( propertyAsString( value, "_id" ) ); sb.append( "\n Status: " ).append( propertyAsString( value, "status" ) ); sb.append( "\n Error: " ).append( propertyAsString( value, "error" ) ); sb.append( "\n" ); } } } return sb.toString(); }
Source:
public void do_not_update_rule_with_removed_status() { db.rules().insert(RuleTesting.newRule(RULE_KEY).setStatus(REMOVED)); dbSession.commit(); RuleUpdate update = createForPluginRule(RULE_KEY) .setTags(Sets.newHashSet("java9")) .setOrganization(db.getDefaultOrganization()); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Rule with REMOVED status cannot be updated: squid:S001"); underTest.update(dbSession, update, db.getDefaultOrganization(), userSessionRule); }

Target:
public void do_not_update_rule_with_removed_status() { db.rules().insert(newRule(RULE_KEY).setStatus(RuleStatus.REMOVED)); dbSession.commit(); RuleUpdate update = createForPluginRule(RULE_KEY) .setTags(Sets.newHashSet("java9")) .setOrganization(db.getDefaultOrganization()); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Rule with REMOVED status cannot be updated: squid:S001"); underTest.update(dbSession, update, db.getDefaultOrganization(), userSessionRule); }
Source:
public void createConnectorInstances(final PersistentObject container, final List<SConnectorDefinition> connectors, final String containerType) throws SBonitaException { final List<SConnectorInstance> connectorInstances = new ArrayList<SConnectorInstance>(connectors.size()); int executionOrder = 0; for (final SConnectorDefinition sConnectorDefinition : connectors) { final int executionOrder1 = executionOrder++; final SConnectorInstance connectorInstance = createConnectorInstanceObject(container, containerType, sConnectorDefinition, executionOrder1); connectorInstances.add(connectorInstance); } final CreateConnectorInstances transaction = new CreateConnectorInstances(connectorInstances, connectorInstanceService); transaction.execute(); }

Target:
public void createConnectorInstances(final PersistentObject container, final List<SConnectorDefinition> connectors, final String containerType) throws SBonitaException { final List<SConnectorInstance> connectorInstances = new ArrayList<SConnectorInstance>(connectors.size()); int executionOrder = 0; for (final SConnectorDefinition sConnectorDefinition : connectors) { final SConnectorInstance connectorInstance = createConnectorInstanceObject(container, containerType, sConnectorDefinition, executionOrder++); connectorInstances.add(connectorInstance); } final CreateConnectorInstances transaction = new CreateConnectorInstances(connectorInstances, connectorInstanceService); transaction.execute(); }
Source:
public void connectionDestroyed(final Object connectionID) { if (logger.isTraceEnabled()) { logger.trace("Connection removed " + connectionID + " from server " + this.server, new Exception("trace")); } ConnectionEntry conn = connections.get(connectionID); if (conn != null && !conn.connection.isSupportReconnect()) { RemotingConnection removedConnection = removeConnection(connectionID); if (removedConnection != null) { try { server.callBrokerPlugins(server.hasBrokerPlugins() ? plugin -> plugin.afterDestroyConnection(removedConnection) : null); } catch (Exception e) { throw new IllegalStateException("Error executing afterDestroyConnection plugin method: " + e.getMessage(), e); } } conn.connection.fail(new ActiveMQRemoteDisconnectException()); } }

Target:
public void connectionDestroyed(final Object connectionID) { if (logger.isTraceEnabled()) { logger.trace("Connection removed " + connectionID + " from server " + this.server, new Exception("trace")); } ConnectionEntry conn = connections.get(connectionID); if (conn != null && !conn.connection.isSupportReconnect()) { RemotingConnection removedConnection = removeConnection(connectionID); if (removedConnection != null) { try { server.callBrokerPlugins(server.hasBrokerPlugins() ? plugin -> plugin.afterDestroyConnection(removedConnection) : null); } catch (Throwable t) { logger.warn("Error executing afterDestroyConnection plugin method: {}", t.getMessage(), t); } } conn.connection.fail(new ActiveMQRemoteDisconnectException()); } }
Source:
private void move() { ArrayList<DiskImage> disks = (ArrayList<DiskImage>) getSelectedItems(); if (disks == null || getWindow() != null) { return; } MoveDiskModel model = new MoveDiskModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().moveDisksTitle()); model.setHashName("move_disks"); model.setEntity(this); model.setDataCenterId(disks.get(0).getStoragePoolId()); model.init(disks); model.startProgress(null); }

Target:
private void move() { ArrayList<DiskImage> disks = (ArrayList<DiskImage>) getSelectedItems(); if (disks == null || disks.isEmpty() || getWindow() != null) { return; } MoveDiskModel model = new MoveDiskModel(); setWindow(model); model.setTitle(ConstantsManager.getInstance().getConstants().moveDisksTitle()); model.setHashName("move_disks"); model.setEntity(this); model.setDataCenterId(disks.get(0).getStoragePoolId()); model.init(disks); model.startProgress(null); }
Source:
private void createBackButton() { ImageButton goback = (ImageButton) llLayout.findViewById( R.id.backToSentSurveys); goback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DomainEventPublisher.instance().unSubscribe( createValueSubscriber()); getActivity().onBackPressed(); } } ); }

Target:
private void createBackButton() { ImageButton goback = (ImageButton) llLayout.findViewById( R.id.backToSentSurveys); goback.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().onBackPressed(); } } ); }
Source:
protected void updateVmDeviceAddress(final String address, final VmDevice vmDevice) { vmDevice.setAddress(address); getCompensationContext().snapshotEntity(vmDevice); vmDeviceDao.update(vmDevice); getCompensationContext().stateChanged(); }

Target:
protected void updateVmDeviceAddress(final String address, final VmDevice vmDevice) { vmDevice.setAddress(address); getCompensationContext().snapshotEntity(vmDevice); getCompensationContext().stateChanged(); vmDeviceDao.update(vmDevice); }
Source:
public void testMultipleBlockAddNotify() throws InterruptedException { final int numOfListener = 3; final int numOfBlockPut = 10; final int numOfKeysPerBlock = 10; final int timeoutInMillisecond = 500; final int blockIdBase = 0x80; final CountDownLatch countDownLatch = new CountDownLatch(numOfListener * numOfBlockPut); final MemoryStoreImpl memoryStoreImpl = (MemoryStoreImpl) memoryStore; for (int i = 0; i < numOfListener; i++) { final MemoryStoreTestUtils.BlockAddListenerImpl listener = new MemoryStoreTestUtils.BlockAddListenerImpl(countDownLatch, numOfKeysPerBlock); memoryStore.registerBlockUpdateListener(listener); } for (int i = 0; i < numOfBlockPut; i++) { final int blockId = blockIdBase + i; final Map<Long, Object> data = new HashMap<>(); final long keyIdStart = (blockId * numOfKeysPerBlock); for (int j = 0; j < numOfKeysPerBlock; j++) { final long keyId = keyIdStart + j; data.put(keyId, new Long(keyId)); } memoryStoreImpl.putBlock(blockId, data); } countDownLatch.await(timeoutInMillisecond, TimeUnit.MILLISECONDS); assertEquals(0, countDownLatch.getCount()); }

Target:
public void testMultipleBlockAddNotify() throws InterruptedException { final int numOfListener = 3; final int numOfBlockPut = 10; final int numOfKeysPerBlock = 10; final int timeoutMS = 500; final int blockIdBase = 0x80; final CountDownLatch countDownLatch = new CountDownLatch(numOfListener * numOfBlockPut); final MemoryStoreImpl memoryStoreImpl = (MemoryStoreImpl) memoryStore; for (int i = 0; i < numOfListener; i++) { final BlockUpdateListener listener = new MemoryStoreTestUtils.BlockUpdateListenerImpl(countDownLatch, null, numOfKeysPerBlock); memoryStore.registerBlockUpdateListener(listener); } for (int i = 0; i < numOfBlockPut; i++) { final int blockId = blockIdBase + i; final Map<Long, Object> data = new HashMap<>(); final long keyIdStart = (blockId * numOfKeysPerBlock); for (int keyOffset = 0; keyOffset < numOfKeysPerBlock; keyOffset++) { final long keyId = keyIdStart + keyOffset; data.put(keyId, keyId); } memoryStoreImpl.putBlock(blockId, data); } assertTrue(countDownLatch.await(timeoutMS, TimeUnit.MILLISECONDS)); }
Source:
public void getAndIncrement( String counterName, AsyncCallback<Long> responder ) { try { Invoker.invokeAsync( ATOMIC_MANAGER_SERVER_ALIAS, "getAndIncrement", new Object[] { Backendless.getApplicationId(), Backendless.getVersion(), counterName }, new AtomicCallback( responder ) ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } }

Target:
public void getAndIncrement( String counterName, AsyncCallback<Long> responder ) { try { getAndIncrement( counterName ); } catch( Throwable e ) { if( responder != null ) responder.handleFault( new BackendlessFault( e ) ); } }
Source:
public static boolean isValidFormat(String format, String dateAsString) { Date date = null; if (dateAsString != null) { try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); date = simpleDateFormat.parse(dateAsString); if (!dateAsString.equals(simpleDateFormat.format(date))) { date = null; } } catch (ParseException exception) { OpenMRS.getInstance().getOpenMRSLogger().w("Failed to validate date format :" + dateAsString + " caused by " + exception.toString()); } return date != null; } else { return false; } }

Target:
public static boolean isValidFormat(String format, String dateAsString) { Date date = null; if (dateAsString != null) { try { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); date = simpleDateFormat.parse(dateAsString); if (!dateAsString.equals(simpleDateFormat.format(date))) { date = null; } } catch (ParseException exception) { OpenMRS.getInstance().getOpenMRSLogger().w("Failed to validate date format :" + dateAsString + " caused by " + exception.toString()); } return date != null; } return false; }
Source:
public String addNode(Node node, String suggestedId) { nodes.add(node); return null; }

Target:
public String addNode(Node node, String suggestedId) { nodes.add(node); return suggestedId; }
Source:
public boolean saveValue(String key, String value) { if (!isKeyValid(key, "saveValue")) { return false; } if (value == null) { SmartStoreLogger.w(TAG, "saveValue: Invalid value supplied: " + key); return false; } long startNanoTime = System.nanoTime(); try (FileOutputStream f = new FileOutputStream(getFileForKey(key)); EncrypterOutputStream outputStream = new EncrypterOutputStream(f, encryptionKey)) { outputStream.write(value.getBytes(StandardCharsets.UTF_8)); return true; } catch (Exception e) { SmartStoreLogger.e(TAG, "IOException occurred while saving value to filesystem", e); return false; } }

Target:
public boolean saveValue(String key, String value) { if (!isKeyValid(key, "saveValue")) { return false; } if (value == null) { SmartStoreLogger.w(TAG, "saveValue: Invalid value supplied: " + value); return false; } long startNanoTime = System.nanoTime(); try (FileOutputStream f = new FileOutputStream(getFileForKey(key)); EncrypterOutputStream outputStream = new EncrypterOutputStream(f, encryptionKey)) { outputStream.write(value.getBytes(StandardCharsets.UTF_8)); return true; } catch (Exception e) { SmartStoreLogger.e(TAG, "IOException occurred while saving value to filesystem", e); return false; } }
Source:
private WebClient createClientForUser(final String id) throws Exception { User u = User.getById(id, true); final ApiTokenProperty t = u.getProperty(ApiTokenProperty.class); final String token = t.getApiTokenInsecure(); WebClient wc = j.createWebClient(); wc.addRequestHeader("Authorization", "Basic " + Scrambler.scramble(id + ":" + token)); return wc; }

Target:
private WebClient createClientForUser(final String id) throws Exception { User u = User.getById(id, true); WebClient wc = j.createWebClient(); wc.withBasicApiToken(u); return wc; }
Source:
public SuccessfulResponse addResponse(Address sender, Response response) { if (response.isSuccessful()) { return (SuccessfulResponse) response; } if (response instanceof ExceptionResponse) { throw ResponseCollectors.wrapRemoteException(sender, ((ExceptionResponse) response).getException()); } if (response instanceof UnsureResponse) { hasUnsureResponse = true; return null; } else if (response instanceof CacheNotFoundResponse) { hasSuspectResponse = true; return null; } throw ResponseCollectors.unexpectedResponse(response); }

Target:
public SuccessfulResponse addResponse(Address sender, Response response) { if (response.isSuccessful()) { return (SuccessfulResponse) response; } if (response instanceof ExceptionResponse) { throw ResponseCollectors.wrapRemoteException(sender, ((ExceptionResponse) response).getException()); } if (response instanceof UnsureResponse) { return null; } else if (response instanceof CacheNotFoundResponse) { hasSuspectResponse = true; return null; } throw ResponseCollectors.unexpectedResponse(response); }
Source:
public void onRTPSessionDestroy(RTPSession rtpSession) { try{ String entryId = Utils.getEntryIdFromRTPSession(rtpSession); logger.info("Entry removed [" + entryId + "]"); KalturaEntryDataPersistence.entriesMapCleanUp(); } catch (Exception e){ logger.info("Error" + e.getMessage()); } }

Target:
public void onRTPSessionDestroy(RTPSession rtpSession) { try{ logger.debug("onRTPSessionDestroy - [" + rtpSession.getSessionId() + "]"); String entryId = Utils.getEntryIdFromRTPSession(rtpSession); logger.info("Entry removed [" + entryId + "]"); KalturaEntryDataPersistence.entriesMapCleanUp(); } catch (Exception e){ logger.info("Error" + e.getMessage()); } }
Source:
public void testDiscardAfterSkipPast() throws Exception { try { m_pbd = PersistentBinaryDeque.builder(TEST_NONCE, TEST_DIR, logger).compression(true) .requiresId(true) .initialExtraHeader(m_metadata, SERIALIZER).build(); long seqNo = 1; int numSegments = 3; for (int i=0; i<numSegments; i++) { if (i>0) { m_pbd.updateExtraHeader(null); } for (int j=0; j<3; j++) { long startSeqNo = seqNo + i*3*10 + j*10; m_pbd.offer(DBBPool.wrapBB(getFilledSmallBuffer(0)), startSeqNo, startSeqNo + 9); } } long lastSeqNo = numSegments*3*10; assertEquals(numSegments, getSortedDirectoryListing().size()); BinaryDequeReader<ExtraHeaderMetadata> reader = m_pbd.openForRead("testreader"); BBContainer cont = reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY); reader.skipPast(lastSeqNo); assertEquals(numSegments, getSortedDirectoryListing().size()); cont.discard(); assertEquals(1, getSortedDirectoryListing().size()); } catch(Throwable t) { t.printStackTrace(); } }

Target:
public void testDiscardAfterSkipPast() throws Exception { m_pbd = PersistentBinaryDeque.builder(TEST_NONCE, TEST_DIR, logger).compression(true) .requiresId(true) .initialExtraHeader(m_metadata, SERIALIZER).build(); long seqNo = 1; int numSegments = 3; for (int i=0; i<numSegments; i++) { if (i>0) { m_pbd.updateExtraHeader(null); } for (int j=0; j<3; j++) { long startSeqNo = seqNo + i*3*10 + j*10; m_pbd.offer(DBBPool.wrapBB(getFilledSmallBuffer(0)), startSeqNo, startSeqNo + 9); } } long lastSeqNo = numSegments*3*10; assertEquals(numSegments, getSortedDirectoryListing().size()); BinaryDequeReader<ExtraHeaderMetadata> reader = m_pbd.openForRead("testreader"); BBContainer cont = reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY); reader.skipPast(lastSeqNo); assertEquals(numSegments, getSortedDirectoryListing().size()); cont.discard(); assertEquals(1, getSortedDirectoryListing().size()); }
Source:
private void complete() { if (isRequestStarted()) { final boolean hasCommands = !commands.isEmpty(); if (hasCommands && roolback) { LOGGER.log(Level.FINEST, "Performing rollback for commands in current requrest."); final AbstractCanvasHandler canvasHandler = getCurrentSession().getCanvasHandler(); commands.forEach(c -> c.undo(canvasHandler)); } else if (hasCommands) { LOGGER.log(Level.FINEST, "Adding commands for current request into registry [size=" + commands.size() + "]"); getRegistry().register(new CompositeCommand.Builder<AbstractCanvasHandler, CanvasViolation>() .addCommands(commands.stream().collect(Collectors.toList())) .build()); commandRegisteredEvent.fire(new CommandRegisteredEvent()); } LOGGER.log(Level.FINEST, "Current client request completed."); } else { LOGGER.log(Level.WARNING, "Current client request has not been started."); } clear(); }

Target:
private void complete() { if (isRequestStarted()) { final boolean hasCommands = !commands.isEmpty(); if (hasCommands && roolback) { LOGGER.log(Level.FINEST, "Performing rollback for commands in current requrest."); final AbstractCanvasHandler canvasHandler = getCurrentSession().getCanvasHandler(); commands.forEach(c -> c.undo(canvasHandler)); } else if (hasCommands) { LOGGER.log(Level.FINEST, "Adding commands for current request into registry [size=" + commands.size() + "]"); getRegistry().register(new CompositeCommand.Builder<AbstractCanvasHandler, CanvasViolation>() .addCommands(new ArrayList<>(commands)) .build()); } LOGGER.log(Level.FINEST, "Current client request completed."); } else { LOGGER.log(Level.WARNING, "Current client request has not been started."); } clear(); }
Source:
public void testGetMultipleNull() { InfinispanCommunicationDetailsCache cdc = createCache(); List<CommunicationDetails> id = cdc.getById(null, null); Assert.assertTrue(id.isEmpty()); }

Target:
public void testGetMultipleNull() { cdc.getById(null, null); }
Source:
public int hashCode() { int hash = 5; hash = 97 * hash + (this.event_initiator != null ? this.event_initiator.hashCode() : 0); hash = 97 * hash + (this.event_name != null ? this.event_name.hashCode() : 0); hash = 97 * hash + (int) (this.user_id ^ (this.user_id >>> 32)); hash = 97 * hash + (this.session_id != null ? this.session_id.hashCode() : 0); hash = 97 * hash + (this.ip != null ? this.ip.hashCode() : 0); hash = 97 * hash + (int) (this.timestamp ^ (this.timestamp >>> 32)); return hash; }

Target:
public int hashCode() { return Objects.hashCode(getEvent_initiator(), getEvent_name(), getIp(), getSession_id(), getTimestamp(), getUser_id()); }
Source:
public boolean isForkTask() { if (taskType.equals(SCRIPT_TASK)) { return false; } else if (taskType.equals(FORKED_SCRIPT_TASK)) { return true; } else { throw new IllegalStateException("Unexpected stored task type: " + taskType); } }

Target:
public boolean isForkTask() { if (SCRIPT_TASK.equals(taskType)) { return false; } else if (FORKED_SCRIPT_TASK.equals(taskType)) { return true; } else { throw new IllegalStateException("Unexpected stored task type: " + taskType); } }
Source:
public UpdateCanvasControlPointPositionCommand(final Edge edge, final ControlPoint[] controlPoints) { this.edge = edge; this.controlPoints = controlPoints; oldControlPoints = Stream.of(getControlPoints(edge)) .map(ControlPoint::copy) .toArray(ControlPoint[]::new); ; }

Target:
public UpdateCanvasControlPointPositionCommand(final Edge edge, final ControlPoint[] controlPoints) { this.edge = edge; this.controlPoints = controlPoints; oldControlPoints = Stream.of(getControlPoints(edge)) .map(ControlPoint::copy) .toArray(ControlPoint[]::new); }
Source:
int setBounds (int x, int y, int width, int height, boolean move, boolean resize) { boolean fixWrap = resize && labelHandle != 0 && (style & SWT.WRAP) != 0; if (fixWrap) OS.gtk_widget_set_size_request (labelHandle, -1, -1); int result = super.setBounds (x, y, width, height, move, resize); if (fixWrap) { GtkAllocation allocation = new GtkAllocation(); OS.gtk_widget_get_allocation (handle, allocation); int labelWidth = allocation.width; int labelHeight = allocation.height; OS.gtk_widget_set_size_request (labelHandle, labelWidth, labelHeight); GtkRequisition requisition = new GtkRequisition (); OS.gtk_widget_get_allocation(labelHandle, allocation); allocation.width = labelWidth; allocation.height = labelHeight; gtk_widget_get_preferred_size (labelHandle, requisition); OS.gtk_widget_size_allocate (labelHandle, allocation); } return result; }

Target:
int setBounds (int x, int y, int width, int height, boolean move, boolean resize) { boolean fixWrap = resize && labelHandle != 0 && (style & SWT.WRAP) != 0; if (fixWrap) OS.gtk_widget_set_size_request (labelHandle, -1, -1); int result = super.setBounds (x, y, width, height, move, resize); if (fixWrap) { GtkAllocation allocation = new GtkAllocation(); OS.gtk_widget_get_allocation (handle, allocation); int labelWidth = allocation.width; int labelHeight = allocation.height; OS.gtk_widget_set_size_request (labelHandle, labelWidth, labelHeight); GtkRequisition requisition = new GtkRequisition (); gtk_widget_get_preferred_size (labelHandle, requisition); OS.gtk_widget_get_allocation(labelHandle, allocation); allocation.width = labelWidth; allocation.height = labelHeight; OS.gtk_widget_size_allocate (labelHandle, allocation); } return result; }
Source:
public ArrayInterface setLong(int index, long value) { return setObject(index, value); }

Target:
public Array setLong(int index, long value) { return setObject(index, value); }
Source:
private String encrypt(byte[] plainTextBytes, String keyStorePath, String keyStorePassword, String alias, String keyStoreType, String algorithm) throws FunctionCallException { if (plainTextBytes == null) { throw new FunctionCallException("Plaintext can't be null."); } try { Cipher cipher = Cipher.getInstance(algorithm); KeyStore keyStore = KeyStoreManager.getKeyStore(keyStorePath, keyStorePassword, keyStoreType); Certificate certificate = KeyStoreManager.getCertificateFromStore(keyStore, alias); if (log.isDebugEnabled()) { log.debug("Certificate used for encrypting : " + certificate); } cipher.init(Cipher.ENCRYPT_MODE, certificate.getPublicKey()); byte[] cipherText = cipher.doFinal(plainTextBytes); if (log.isDebugEnabled()) { log.debug(String.format("Successfully encrypted data using the algorithm '%s'", algorithm)); } return Base64.getEncoder().encodeToString(cipherText); } catch (NoSuchAlgorithmException | NoSuchPaddingException | KeyStoreException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new FunctionCallException("An error occurred while encrypting data.", e); } }

Target:
private String encrypt(byte[] plainTextBytes, String keyStorePath, String keyStorePassword, String alias, String keyStoreType, String algorithm) throws FunctionCallException { if (plainTextBytes == null) { throw new FunctionCallException("Plaintext can't be null."); } try { Cipher cipher = getCipherInstance(algorithm); KeyStore keyStore = KeyStoreManager.getKeyStore(keyStorePath, keyStorePassword, keyStoreType); Certificate certificate = KeyStoreManager.getCertificateFromStore(keyStore, alias); if (log.isDebugEnabled()) { log.debug("Certificate used for encrypting : " + certificate); } cipher.init(Cipher.ENCRYPT_MODE, certificate.getPublicKey()); byte[] cipherText = cipher.doFinal(plainTextBytes); if (log.isDebugEnabled()) { log.debug(String.format("Successfully encrypted data using the algorithm '%s'", algorithm)); } return Base64.getEncoder().encodeToString(cipherText); } catch (NoSuchAlgorithmException | NoSuchPaddingException | KeyStoreException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { throw new FunctionCallException("An error occurred while encrypting data.", e); } }
Source:
private void testOldCourseTable(CourseDetailsBundle oldCourse, CourseTable courseTable) { assertEquals(oldCourse.feedbackSessions.size(), courseTable.getRows().size()); List<HomeFeedbackSessionRow> sessions = courseTable.getRows(); HomeFeedbackSessionRow publishedRow = sessions.get(0); HomeFeedbackSessionRow closedRow = sessions.get(1); HomeFeedbackSessionRow submittedClosedRow = sessions.get(2); int accumlativeOffset = courses.get(0).feedbackSessions.size(); int index = 0 + accumlativeOffset; testFeedbackSession(index++, publishedRow, publishedSession, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_PENDING + Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_CLOSED, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_PUBLISHED, "Closed", "Yes"); testFeedbackSession(index++, closedRow, closedSession, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_PENDING + Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_CLOSED, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_NOT_PUBLISHED, "Closed", "No"); testFeedbackSession(index++, submittedClosedRow, submittedClosedSession, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_SUBMITTED + Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_CLOSED, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_NOT_PUBLISHED, "Closed", "No"); }

Target:
private void testOldCourseTable(CourseDetailsBundle oldCourse, CourseTable courseTable) { assertEquals(oldCourse.feedbackSessions.size(), courseTable.getRows().size()); List<HomeFeedbackSessionRow> sessions = courseTable.getRows(); HomeFeedbackSessionRow publishedRow = sessions.get(0); HomeFeedbackSessionRow closedRow = sessions.get(1); HomeFeedbackSessionRow submittedClosedRow = sessions.get(2); int accumlativeOffset = courses.get(0).feedbackSessions.size(); int index = 0 + accumlativeOffset; testFeedbackSession(index++, publishedRow, publishedSession, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_PENDING + Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_CLOSED, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_PUBLISHED, "Closed", "Published"); testFeedbackSession(index++, closedRow, closedSession, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_PENDING + Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_CLOSED, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_NOT_PUBLISHED, "Closed", "Not Published"); testFeedbackSession(index++, submittedClosedRow, submittedClosedSession, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_SUBMITTED + Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_CLOSED, Const.Tooltips.STUDENT_FEEDBACK_SESSION_STATUS_NOT_PUBLISHED, "Closed", "Not Published"); }
Source:
private String mkKey(Class clazz, String propertyName) { return clazz.getCanonicalName() + "__" + propertyName; }

Target:
private String mkKey(Class clazz, String propertyName) { return clazz.getName() + "__" + propertyName; }
Source:
private void reportMetrics(DatastreamRecordMetadata metadata, DatastreamTask task, DatastreamProducerRecord record) { synchronized (_sourceToDestinationLatencyMs) { _sourceToDestinationLatencyMs = System.currentTimeMillis() - record.getEventsTimestamp(); if (_sourceToDestinationLatencyMs <= _availabilityThresholdSlaMs) { EVENTS_PRODUCED_WITHIN_SLA.inc(); } else { _dynamicMetricsManager.createOrUpdateCounter(this.getClass(), metadata.getTopic(), EVENTS_PRODUCED_OUTSIDE_SLA, 1); _logger.warn( String.format("Event latency of %d for source %s, topic %s, partition %d exceeded SLA of %d millseconds", _sourceToDestinationLatencyMs, task.getDatastreamSource().getConnectionString(), metadata.getTopic(), metadata.getPartition(), _availabilityThresholdSlaMs)); } TOTAL_EVENTS_PRODUCED.inc(); } EVENT_PRODUCE_RATE.mark(record.getEvents().size()); record.getEvents().forEach(e -> EVENT_BYTES_PRODUCE_RATE.mark(e.getKey().length + e.getValue().length)); }

Target:
private void reportMetrics(DatastreamRecordMetadata metadata, DatastreamTask task, DatastreamProducerRecord record) { _sourceToDestinationLatencyMs = System.currentTimeMillis() - record.getEventsTimestamp(); if (_sourceToDestinationLatencyMs <= _availabilityThresholdSlaMs) { EVENTS_PRODUCED_WITHIN_SLA.inc(); } else { _dynamicMetricsManager.createOrUpdateCounter(this.getClass(), metadata.getTopic(), EVENTS_PRODUCED_OUTSIDE_SLA, 1); _logger.warn( String.format("Event latency of %d for source %s, topic %s, partition %d exceeded SLA of %d millseconds", _sourceToDestinationLatencyMs, task.getDatastreamSource().getConnectionString(), metadata.getTopic(), metadata.getPartition(), _availabilityThresholdSlaMs)); } TOTAL_EVENTS_PRODUCED.inc(); EVENT_PRODUCE_RATE.mark(record.getEvents().size()); record.getEvents().forEach(e -> EVENT_BYTES_PRODUCE_RATE.mark(e.getKey().length + e.getValue().length)); }
Source:
public DBUpdatesWrapper getUpdatesSince(long sequenceNumber) throws DataNotFoundException { DBUpdatesWrapper dbUpdatesWrapper = new DBUpdatesWrapper(); try { TransactionLogIterator transactionLogIterator = db.getUpdatesSince(sequenceNumber); boolean flag = true; while (transactionLogIterator.isValid()) { TransactionLogIterator.BatchResult result = transactionLogIterator.getBatch(); long currSequenceNumber = result.sequenceNumber(); if (flag && currSequenceNumber > 1 + sequenceNumber) { throw new DataNotFoundException("Unable to read data from " + "RocksDB wal to get delta updates. It may have already been" + "flushed to SSTs."); } flag = false; if (currSequenceNumber == sequenceNumber) { transactionLogIterator.next(); continue; } WriteBatch writeBatch = result.writeBatch(); byte[] writeBatchData = writeBatch.data(); dbUpdatesWrapper.addWriteBatch(writeBatchData, result.sequenceNumber()); transactionLogIterator.next(); } } catch (RocksDBException e) { LOG.error("Unable to get delta updates since sequenceNumber ", sequenceNumber, e); } return dbUpdatesWrapper; }

Target:
public DBUpdatesWrapper getUpdatesSince(long sequenceNumber) throws SequenceNumberNotFoundException { DBUpdatesWrapper dbUpdatesWrapper = new DBUpdatesWrapper(); try { TransactionLogIterator transactionLogIterator = db.getUpdatesSince(sequenceNumber); boolean checkValidStartingSeqNumber = true; while (transactionLogIterator.isValid()) { TransactionLogIterator.BatchResult result = transactionLogIterator.getBatch(); long currSequenceNumber = result.sequenceNumber(); if (checkValidStartingSeqNumber && currSequenceNumber > 1 + sequenceNumber) { throw new SequenceNumberNotFoundException("Unable to read data from" + " RocksDB wal to get delta updates. It may have already been" + "flushed to SSTs."); } checkValidStartingSeqNumber = false; if (currSequenceNumber <= sequenceNumber) { transactionLogIterator.next(); continue; } dbUpdatesWrapper.addWriteBatch(result.writeBatch().data(), result.sequenceNumber()); transactionLogIterator.next(); } } catch (RocksDBException e) { LOG.error("Unable to get delta updates since sequenceNumber ", sequenceNumber, e); } return dbUpdatesWrapper; }
Source:
private TuningParameterUtils() { }

Target:
public TuningParameterUtils() { httpClient = HttpClients.createDefault(); }
Source:
default Duration getTotalDuration() { return StreamSupport.stream(getDataSources().spliterator(), false) .map(spec -> BaseQuery.initDuration(spec.getQuerySegmentSpec())) .reduce(new Duration(0), Duration::plus); }

Target:
default Duration getTotalDuration() { Duration totalDuration = new Duration(0); for (DataSourceWithSegmentSpec spec : getDataSources()) { totalDuration = totalDuration.plus(Queries.getTotalDuration(spec.getQuerySegmentSpec())); } return totalDuration; }
Source:
public void testUnmapDoesntCrashJVM() throws Exception { final File file = temporaryFolder.newFile("some_mmap_file"); try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { final byte[] data = new byte[4096]; Arrays.fill(data, (byte) 0x5A); os.write(data); } final MappedByteBuffer mappedByteBuffer; try (final FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.READ)) { mappedByteBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, 4096); } Assert.assertEquals((byte) 0x5A, mappedByteBuffer.get(0)); ByteBufferUtils.unmap(mappedByteBuffer); ByteBufferUtils.unmap(mappedByteBuffer); }

Target:
public void testUnmapDoesntCrashJVM() throws Exception { final File file = temporaryFolder.newFile("some_mmap_file"); try (final OutputStream os = new BufferedOutputStream(new FileOutputStream(file))) { final byte[] data = new byte[4096]; Arrays.fill(data, (byte) 0x5A); os.write(data); } final MappedByteBuffer mappedByteBuffer = Files.map(file); Assert.assertEquals((byte) 0x5A, mappedByteBuffer.get(0)); ByteBufferUtils.unmap(mappedByteBuffer); ByteBufferUtils.unmap(mappedByteBuffer); }