auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void expunge(Integer noOfChargesToExpungeQueryParam) { if (expungeConfig.isExpungeChargesEnabled()) { int noOfChargesToExpunge = getNumberOfChargesToExpunge(noOfChargesToExpungeQueryParam); int noOfChargesProcessed = 0; while (noOfChargesProcessed < noOfChargesToExpunge) { Optional<ChargeEntity> mayBeChargeEntity = chargeDao.findChargeToExpunge(expungeConfig.getMinimumAgeOfChargeInDays(), expungeConfig.getExcludeChargesParityCheckedWithInDays() ); mayBeChargeEntity.ifPresent(chargeEntity -> { if (hasFinalisedState(chargeEntity) && parityCheckService.parityCheckChargeForExpunger(chargeEntity)) { chargeDao.expungeCharge(chargeEntity.getId()); logger.info("Charge expunged from connector {}", kv(PAYMENT_EXTERNAL_ID, chargeEntity.getExternalId())); } else { chargeDao.updateChargeParityCheckDate(chargeEntity.getId(), ZonedDateTime.now(UTC)); logger.info("Charge does not meet expunging criteria from connector {}", kv(PAYMENT_EXTERNAL_ID, chargeEntity.getExternalId())); } }); if (mayBeChargeEntity.isEmpty()) { break; } noOfChargesProcessed++; } } else { logger.info("Charge expunging feature is disabled. No charges have been expunged"); } }

Target:
public void expunge(Integer noOfChargesToExpungeQueryParam) { if (!expungeConfig.isExpungeChargesEnabled()) { logger.info("Charge expunging feature is disabled. No charges have been expunged"); } else { int noOfChargesToExpunge = getNumberOfChargesToExpunge(noOfChargesToExpungeQueryParam); int minimumAgeOfChargeInDays = expungeConfig.getMinimumAgeOfChargeInDays(); int createdWithinLast = expungeConfig.getExcludeChargesParityCheckedWithInDays(); IntStream.range(0, noOfChargesToExpunge).forEach(number -> { chargeDao.findChargeToExpunge(minimumAgeOfChargeInDays, createdWithinLast) .ifPresent(this::parityCheckAndExpungeIfMet); }); } }
Source:
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { getPreferenceManager().setSharedPreferencesName(ADMIN_PREFERENCES); setPreferencesFromResource(R.xml.main_menu_access_preferences, rootKey); ((CollectAbstractActivity) getActivity()).initToolbar(getPreferenceScreen().getTitle()); findPreference(KEY_EDIT_SAVED).setEnabled((Boolean) AdminSharedPreferences.getInstance().get(ALLOW_OTHER_WAYS_OF_EDITING_FORM)); }

Target:
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { getPreferenceManager().setSharedPreferencesName(ADMIN_PREFERENCES); setPreferencesFromResource(R.xml.main_menu_access_preferences, rootKey); findPreference(KEY_EDIT_SAVED).setEnabled((Boolean) AdminSharedPreferences.getInstance().get(ALLOW_OTHER_WAYS_OF_EDITING_FORM)); }
Source:
public List<URI> getDependencies(URI uri) { Set<URI> dependencies = new LinkedHashSet<URI>(); dependencies.add(uri); for (IConfigurationElement element : modelExtensions) { if (ModelsReader.MODEL_ELEMENT_NAME.equals(element.getName())) { String extension = element.getAttribute(EXTENSION_ATTRIBUTE); if (extension != null && !"".equals(extension.trim())) { URI dependencyURI = uri.trimFileExtension().appendFileExtension(extension); if (URIConverter.INSTANCE.exists(dependencyURI, null)) { dependencies.add(dependencyURI); } } } } return new ArrayList<URI>(dependencies); }

Target:
public List<URI> getDependencies(URI uri) { Set<URI> dependencies = new LinkedHashSet<URI>(); for (String fileExtension : fileExtensions) { URI dependencyURI = uri.trimFileExtension().appendFileExtension(fileExtension); if (URIConverter.INSTANCE.exists(dependencyURI, null)) { dependencies.add(dependencyURI); } } return new ArrayList<URI>(dependencies); }
Source:
public void setUp() throws Exception { locator = cluster.startLocatorVM(0); locatorPort = locator.getPort(); client = cluster.startClientVM(4, c -> c.withPoolSubscription(true).withLocatorConnection((locatorPort))); }

Target:
public void setUp() throws Exception { locator = cluster.startLocatorVM(0); locatorPort = locator.getPort(); }
Source:
private List<AccountInfo> suggestAccount(VisibilityControl visibilityControl) throws OrmException { String a = query; String b = a + MAX_SUFFIX; Map<Account.Id, AccountInfo> r = new LinkedHashMap<>(); Map<Account.Id, String> queryEmail = new HashMap<>(); for (Account p : dbProvider.get().accounts() .suggestByFullName(a, b, limit)) { if (p.isActive()) { addSuggestion(r, p.getId(), visibilityControl); } } if (r.size() < limit) { for (Account p : dbProvider.get().accounts() .suggestByPreferredEmail(a, b, limit - r.size())) { if (p.isActive()) { addSuggestion(r, p.getId(), visibilityControl); } } } if (r.size() < limit) { for (AccountExternalId e : dbProvider.get().accountExternalIds() .suggestByEmailAddress(a, b, limit - r.size())) { if (!r.containsKey(e.getAccountId())) { Account p = accountCache.get(e.getAccountId()).getAccount(); if (p.isActive()) { queryEmail.put(e.getAccountId(), e.getEmailAddress()); addSuggestion(r, p.getId(), visibilityControl); } } } } accountLoader.fill(); for (Map.Entry<Account.Id, String> p : queryEmail.entrySet()) { r.get(p.getKey()).email = p.getValue(); } return Lists.newArrayList(r.values()); }

Target:
private List<AccountInfo> suggestAccount(VisibilityControl visibilityControl) throws OrmException { String a = query; String b = a + MAX_SUFFIX; Map<Account.Id, AccountInfo> r = new LinkedHashMap<>(); Map<Account.Id, String> queryEmail = new HashMap<>(); for (Account p : dbProvider.get().accounts() .suggestByFullName(a, b, limit)) { if (p.isActive()) { addSuggestion(r, p.getId(), visibilityControl); } } if (r.size() < limit) { for (Account p : dbProvider.get().accounts() .suggestByPreferredEmail(a, b, limit - r.size())) { if (p.isActive()) { addSuggestion(r, p.getId(), visibilityControl); } } } if (r.size() < limit) { for (AccountExternalId e : dbProvider.get().accountExternalIds() .suggestByEmailAddress(a, b, limit - r.size())) { if (!r.containsKey(e.getAccountId())) { Account p = accountCache.get(e.getAccountId()).getAccount(); if (p.isActive()) { if (addSuggestion(r, p.getId(), visibilityControl)) { queryEmail.put(e.getAccountId(), e.getEmailAddress()); } } } } } accountLoader.fill(); for (Map.Entry<Account.Id, String> p : queryEmail.entrySet()) { AccountInfo info = r.get(p.getKey()); if (info != null) { info.email = p.getValue(); } } return new ArrayList<>(r.values()); }
Source:
public void beginTrainingWithOptions() { String trainingSetSource = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix( "Invoice"); formTrainingAsyncClient.beginTraining(trainingSetSource, true, trainModelOptions, Duration.ofSeconds(5) ).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); END: com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginTraining#string-boolean-trainModelOptions-Duration }

Target:
public void beginTrainingWithOptions() { String trainingFilesUrl = "{training-set-SAS-URL}"; TrainModelOptions trainModelOptions = new TrainModelOptions().setIncludeSubFolders(false).setPrefix("Invoice"); formTrainingAsyncClient.beginTraining(trainingFilesUrl, true, trainModelOptions, Duration.ofSeconds(5)).subscribe(recognizePollingOperation -> { recognizePollingOperation.getFinalResult().subscribe(customFormModel -> { System.out.printf("Model Id: %s%n", customFormModel.getModelId()); System.out.printf("Model Status: %s%n", customFormModel.getModelStatus()); customFormModel.getSubModels().forEach(customFormSubModel -> customFormSubModel.getFieldMap().forEach((key, customFormModelField) -> System.out.printf("Form Type: %s Field Text: %s Field Accuracy: %s%n", key, customFormModelField.getName(), customFormModelField.getAccuracy()))); }); }); END: com.azure.ai.formrecognizer.training.FormTrainingAsyncClient.beginTraining#string-boolean-trainModelOptions-Duration }
Source:
public void deleteByCutOffDate_shouldDeleteOlderTokens() { long days_till_expiry = -7; long days_longer_than_expiry = -8; ZonedDateTime cut_off_date = ZonedDateTime.now(ZoneId.of("UTC")).plusDays(days_till_expiry); ZonedDateTime today = ZonedDateTime.now(ZoneId.of("UTC")); ZonedDateTime eight_days_old = ZonedDateTime.now(ZoneId.of("UTC")).plusDays(days_longer_than_expiry); String present_day_tokenId = "token1"; String eight_days_old_tokenId = "token2"; ChargeEntity ChargeTestEntity = new ChargeEntity(); ChargeTestEntity.setId(defaultTestCharge.getChargeId()); TokenEntity present_day_token = TokenEntity.generateNewTokenFor(ChargeTestEntity); present_day_token.setCreatedDate(today); present_day_token.setToken(present_day_tokenId); tokenDao.persist(present_day_token); TokenEntity eight_day_old_token = TokenEntity.generateNewTokenFor(ChargeTestEntity); eight_day_old_token.setCreatedDate(eight_days_old); eight_day_old_token.setToken(eight_days_old_tokenId); tokenDao.persist(eight_day_old_token); tokenDao.deleteTokensOlderThanSpecifiedDate(cut_off_date); assertThat(tokenDao.findByTokenId(eight_days_old_tokenId), is(Optional.empty())); TokenEntity present_token = tokenDao.findByTokenId(present_day_tokenId).get(); assertThat(present_token.getId(), is(notNullValue())); assertThat(present_token.getToken(), is(present_day_tokenId)); assertThat(present_token.getCreatedDate(), is(today)); }

Target:
public void deleteByCutOffDate_shouldDeleteOlderTokens() { long daysTillExpiry = 7; long daysLongerThanExpiry = 8; ZonedDateTime cutOffDate = ZonedDateTime.now(ZoneId.of("UTC")).minusDays(daysTillExpiry); ZonedDateTime today = ZonedDateTime.now(ZoneId.of("UTC")); ZonedDateTime eightDaysOld = ZonedDateTime.now(ZoneId.of("UTC")).minusDays(daysLongerThanExpiry); String presentDayTokenId = "token1"; String eightDaysOldTokenId = "token2"; ChargeEntity ChargeTestEntity = new ChargeEntity(); ChargeTestEntity.setId(defaultTestCharge.getChargeId()); TokenEntity presentDayToken = TokenEntity.generateNewTokenFor(ChargeTestEntity); presentDayToken.setCreatedDate(today); presentDayToken.setToken(presentDayTokenId); tokenDao.persist(presentDayToken); TokenEntity eightDayOldToken = TokenEntity.generateNewTokenFor(ChargeTestEntity); eightDayOldToken.setCreatedDate(eightDaysOld); eightDayOldToken.setToken(eightDaysOldTokenId); tokenDao.persist(eightDayOldToken); tokenDao.deleteTokensOlderThanSpecifiedDate(cutOffDate); assertThat(tokenDao.findByTokenId(eightDaysOldTokenId), is(Optional.empty())); TokenEntity presentToken = tokenDao.findByTokenId(presentDayTokenId).get(); assertThat(presentToken.getId(), is(notNullValue())); assertThat(presentToken.getToken(), is(presentDayTokenId)); assertThat(presentToken.getCreatedDate(), is(today)); }
Source:
public static void setError(Throwable error) { Preconditions.checkNotNull(error); Throwable old = commandErrors.get().peek(); if (old == null) { throw new IllegalStateException(); } if (old == noError) { commandErrors.get().pop(); commandErrors.get().push(error); } }

Target:
public static void setError(Throwable error) { checkNotNull(error); Throwable old = commandErrors.get().peek(); if (old == null) { throw new IllegalStateException(); } if (old == noError) { commandErrors.get().pop(); commandErrors.get().push(error); } }
Source:
public static void setResponseCachedTime(Map<String, String> headers, CachableResponse response) throws ParseException { long responseFetchedTime; String fetchedTime; if (headers != null && (fetchedTime = headers.get(HttpHeaders.DATE)) != null) { SimpleDateFormat format = new SimpleDateFormat(CachingConstants.DATE_PATTERN); Date d = format.parse(fetchedTime); responseFetchedTime = d.getTime(); } else { responseFetchedTime = System.currentTimeMillis(); } response.setResponseFetchedTime(responseFetchedTime); }

Target:
public static void setResponseCachedTime(Map<String, String> headers, CachableResponse response) throws ParseException { long responseFetchedTime; String dateHeaderValue; if (headers != null && (dateHeaderValue = headers.get(HttpHeaders.DATE)) != null) { SimpleDateFormat format = new SimpleDateFormat(CachingConstants.DATE_PATTERN); Date d = format.parse(dateHeaderValue); responseFetchedTime = d.getTime(); } else { responseFetchedTime = System.currentTimeMillis(); } response.setResponseFetchedTime(responseFetchedTime); }
Source:
public Object intercept(InvocationContext ctx) throws Exception { try { beanManager.getContext(RequestScoped.class).isActive(); isRequestContextActive.set(true); return ctx.proceed(); } catch (ContextNotActiveException e) { } return ctx.proceed(); }

Target:
public Object intercept(InvocationContext ctx) throws Exception { try { isRequestContextActive.set(beanManager.getContext(RequestScoped.class).isActive()); return ctx.proceed(); } catch (ContextNotActiveException e) { } return ctx.proceed(); }
Source:
private void showNotification(int downloadedConcepts) { Intent notificationIntent = new Intent(this, SettingsActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); notificationIntent.putExtra(ApplicationConstants.BroadcastActions.CONCEPT_DOWNLOAD_BROADCAST_INTENT_KEY_COUNT, downloadedConcepts); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_openmrs); Notification notification = new NotificationCompat.Builder(this) .setContentTitle(getString(R.string.downloading_concepts_notification_message)) .setTicker(getString(R.string.accessibility_services_app_name_message)) .setContentText(String.valueOf(downloadedConcepts)) .setSmallIcon(R.drawable.ic_stat_notify_download) .setLargeIcon( Bitmap.createScaledBitmap(icon, 128, 128, false)) .setContentIntent(pendingIntent) .setOngoing(true) .build(); startForeground(ApplicationConstants.ServiceNotificationId.CONCEPT_DOWNLOADFOREGROUND_SERVICE, notification); }

Target:
private void showNotification(int downloadedConcepts) { Intent notificationIntent = new Intent(this, SettingsActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); notificationIntent.putExtra(ApplicationConstants.BroadcastActions.CONCEPT_DOWNLOAD_BROADCAST_INTENT_KEY_COUNT, downloadedConcepts); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_openmrs); Notification notification = new NotificationCompat.Builder(this) .setContentTitle(getString(R.string.downloading_concepts_notification_message)) .setTicker(getString(R.string.app_name)) .setContentText(String.valueOf(downloadedConcepts)) .setSmallIcon(R.drawable.ic_stat_notify_download) .setLargeIcon( Bitmap.createScaledBitmap(icon, 128, 128, false)) .setContentIntent(pendingIntent) .setOngoing(true) .build(); startForeground(ApplicationConstants.ServiceNotificationId.CONCEPT_DOWNLOADFOREGROUND_SERVICE, notification); }
Source:
public void subscribe(String topic, int qos) throws MqttException { client.subscribe(topic, qos, "Subscribe sample context", this); subscriptions.add(topic); broadcastState(); }

Target:
public void subscribe(String topic, int qos) throws MqttException { client.subscribe(topic, qos, userContext, this); subscriptions.add(topic); broadcastState(); }
Source:
public void setRecipients(List<Recipient> recipients) { Assert.notEmpty(recipients, "'recipients' must not be empty"); ConcurrentLinkedQueue<Recipient> originalRecipients = this.recipients; this.recipients.clear(); this.recipients.addAll(recipients); if (getBeanFactory() != null) { this.recipients.forEach(recipient -> recipient.setChannelResolver(getChannelResolver())); } if (logger.isDebugEnabled()) { logger.debug("Channel Recipients: " + originalRecipients + " replaced with: " + this.recipients); } }

Target:
public void setRecipients(List<Recipient> recipients) { Assert.notEmpty(recipients, "'recipients' must not be empty"); Queue<Recipient> newRecipients = new ConcurrentLinkedQueue<>(recipients); if (getBeanFactory() != null) { newRecipients.forEach(recipient -> recipient.setChannelResolver(getChannelResolver())); } if (logger.isDebugEnabled()) { logger.debug("Channel Recipients: " + this.recipients + " replaced with: " + newRecipients); } this.recipients = newRecipients; }
Source:
protected void executeCommand() { getParameters().setEntityInfo(getEntityInfo()); setSucceeded(true); if (!images.isEmpty()) { List<DiskImage> imageToRemove = new ArrayList<>(); for (DiskImage image : images) { if (image.getStorageIds().get(0).equals(getParameters().getStorageDomainId())) { image.setStorageIds(Collections.singletonList(getParameters().getStorageDomainId())); image.setStoragePoolId(getParameters().getStoragePoolId()); imageToRemove.add(image); } } RemoveAllVmImagesParameters removeAllVmImagesParameters = new RemoveAllVmImagesParameters(getVmId(), imageToRemove); removeAllVmImagesParameters.setParentCommand(getActionType()); removeAllVmImagesParameters.setEntityInfo(getParameters().getEntityInfo()); removeAllVmImagesParameters.setForceDelete(true); removeAllVmImagesParameters.setParentParameters(getParameters()); ActionReturnValue vdcRetValue = runInternalActionWithTasksContext(ActionType.RemoveAllVmImages, removeAllVmImagesParameters); if (vdcRetValue.getSucceeded()) { getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } else { getReturnValue().setFault(vdcRetValue.getFault()); setSucceeded(false); } } vmAndTemplatesGenerationsDao.deleteOvfGenerations(Collections.singletonList(ovfEntityData.getEntityId())); unregisteredOVFDataDao.removeEntity(ovfEntityData.getEntityId(), null); unregisteredDisksDao.removeUnregisteredDiskRelatedToVM(ovfEntityData.getEntityId(), null); }

Target:
protected void executeCommand() { getParameters().setEntityInfo(getEntityInfo()); setSucceeded(true); if (images != null && !images.isEmpty()) { List<DiskImage> imageToRemove = new ArrayList<>(); for (DiskImage image : images) { if (image.getStorageIds().get(0).equals(getParameters().getStorageDomainId())) { image.setStorageIds(Collections.singletonList(getParameters().getStorageDomainId())); image.setStoragePoolId(getParameters().getStoragePoolId()); imageToRemove.add(image); } } RemoveAllVmImagesParameters removeAllVmImagesParameters = new RemoveAllVmImagesParameters(getVmId(), imageToRemove); removeAllVmImagesParameters.setParentCommand(getActionType()); removeAllVmImagesParameters.setEntityInfo(getParameters().getEntityInfo()); removeAllVmImagesParameters.setForceDelete(true); removeAllVmImagesParameters.setParentParameters(getParameters()); ActionReturnValue vdcRetValue = runInternalActionWithTasksContext(ActionType.RemoveAllVmImages, removeAllVmImagesParameters); if (vdcRetValue.getSucceeded()) { getReturnValue().getVdsmTaskIdList().addAll(vdcRetValue.getInternalVdsmTaskIdList()); } else { getReturnValue().setFault(vdcRetValue.getFault()); setSucceeded(false); } } vmAndTemplatesGenerationsDao.deleteOvfGenerations(Collections.singletonList(ovfEntityData.getEntityId())); unregisteredOVFDataDao.removeEntity(ovfEntityData.getEntityId(), null); unregisteredDisksDao.removeUnregisteredDiskRelatedToVM(ovfEntityData.getEntityId(), null); }
Source:
private void assertFailureOnUntrustedInterface(ClientMessage clientMessage) throws Exception { ClientInvocation invocation = new ClientInvocation(((HazelcastClientProxy) client).client, clientMessage, null); ClientInvocationFuture future = invocation.invoke(); try { future.get(ASSERT_TRUE_EVENTUALLY_TIMEOUT, SECONDS); fail("AuthenticationException was expected."); } catch (ExecutionException e) { assertThat(e.getCause(), is(instanceOf(AccessControlException.class))); } }

Target:
private void assertFailureOnUntrustedInterface(ClientMessage clientMessage) throws Exception { ClientInvocation invocation = new ClientInvocation(((HazelcastClientProxy) client).client, clientMessage, null); ClientInvocationFuture future = invocation.invoke(); try { future.get(ASSERT_TRUE_EVENTUALLY_TIMEOUT, SECONDS); fail("AccessControlException was expected."); } catch (ExecutionException e) { assertThat(e.getCause(), is(instanceOf(AccessControlException.class))); } }
Source:
protected void ExecuteVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getParameters().getInterface().getType()).getInterfaceTranslation()).toString()); this.setVmName(DbFacade.getInstance().getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); if (StringHelper.isNullOrEmpty(getParameters().getInterface().getMacAddress())) { String mac = null; RefObject<String> tempRefObject = new RefObject<String>(mac); MacPoolManager.getInstance().allocateNewMac(tempRefObject); mac = tempRefObject.argvalue; getParameters().getInterface().setMacAddress(mac); } getParameters().getInterface().setSpeed( VmInterfaceType.forValue( getParameters().getInterface().getType()).getSpeed()); getParameters().getInterface().setId(Guid.NewGuid()); getParameters().getInterface().setVmId(getParameters().getVmId()); DbFacade.getInstance() .getVmNetworkInterfaceDAO() .save(getParameters().getInterface()); DbFacade.getInstance() .getVmNetworkStatisticsDAO() .save(getParameters().getInterface().getStatistics()); VmDevice iface = new VmDevice(new VmDeviceId(getParameters().getInterface().getId(), getParameters().getVmId()), VmDeviceCommonUtils.INTERFACE, VmDeviceCommonUtils.BRIDGE, "", 0, "", true, false, false, false); DbFacade.getInstance().getVmDeviceDAO().save(iface); setSucceeded(true); }

Target:
protected void ExecuteVmCommand() { AddCustomValue("InterfaceType", (VmInterfaceType.forValue(getParameters().getInterface().getType()).getInterfaceTranslation()).toString()); this.setVmName(DbFacade.getInstance().getVmStaticDAO().get(getParameters().getVmId()).getvm_name()); if (StringHelper.isNullOrEmpty(getParameters().getInterface().getMacAddress())) { String mac = null; RefObject<String> tempRefObject = new RefObject<String>(mac); MacPoolManager.getInstance().allocateNewMac(tempRefObject); mac = tempRefObject.argvalue; getParameters().getInterface().setMacAddress(mac); } getParameters().getInterface().setSpeed( VmInterfaceType.forValue( getParameters().getInterface().getType()).getSpeed()); getParameters().getInterface().setId(Guid.NewGuid()); getParameters().getInterface().setVmId(getParameters().getVmId()); DbFacade dbFacade = DbFacade.getInstance(); dbFacade .getVmNetworkInterfaceDAO() .save(getParameters().getInterface()); dbFacade .getVmNetworkStatisticsDAO() .save(getParameters().getInterface().getStatistics()); VmDevice iface = new VmDevice(new VmDeviceId(getParameters().getInterface().getId(), getParameters().getVmId()), VmDeviceCommonUtils.INTERFACE, VmDeviceCommonUtils.BRIDGE, "", 0, "", true, false, false, false); dbFacade.getVmDeviceDAO().save(iface); setSucceeded(true); }
Source:
public void run() { int numRetries = 0; InetSocketAddress addr; Socket client = null; while((!shutdown) && (numRetries < 3)){ try { ss = new ServerSocket(); ss.setReuseAddress(true); if (self.getQuorumListenOnAllIPs()) { int port = self.getElectionAddress().getPort(); addr = new InetSocketAddress(port); } else { self.recreateSocketAddresses(self.getId()); addr = self.getElectionAddress(); } LOG.info("My election bind port: " + addr.toString()); setName(addr.toString()); ss.bind(addr); while (!shutdown) { client = ss.accept(); setSockOpts(client); LOG.info("Received connection request " + client.getRemoteSocketAddress()); receiveConnection(client); numRetries = 0; } } catch (IOException e) { LOG.error("Exception while listening", e); if (!(e instanceof SocketTimeoutException)) { numRetries++; } try { ss.close(); Thread.sleep(1000); } catch (IOException ie) { LOG.error("Error closing server socket", ie); } catch (InterruptedException ie) { LOG.error("Interrupted while sleeping. " + "Ignoring exception", ie); } closeSocket(client); if (shutdown) { break; } } } LOG.info("Leaving listener"); if (!shutdown) { LOG.error("As I'm leaving the listener thread, " + "I won't be able to participate in leader " + "election any longer: " + self.getElectionAddress()); } else if (ss != null) { try { ss.close(); } catch (IOException ie) { LOG.debug("Error closing server socket", ie); } } }

Target:
public void run() { int numRetries = 0; InetSocketAddress addr; Socket client = null; while((!shutdown) && (numRetries < 3)){ try { ss = new ServerSocket(); ss.setReuseAddress(true); if (self.getQuorumListenOnAllIPs()) { int port = self.getElectionAddress().getPort(); addr = new InetSocketAddress(port); } else { self.recreateSocketAddresses(self.getId()); addr = self.getElectionAddress(); } LOG.info("My election bind port: " + addr.toString()); setName(addr.toString()); ss.bind(addr); while (!shutdown) { try { client = ss.accept(); setSockOpts(client); LOG.info("Received connection request " + client.getRemoteSocketAddress()); receiveConnection(client); numRetries = 0; } catch (SocketTimeoutException e) { LOG.warn("The socket is listening for the election accepted " + "and it timed out unexpectedly, but will retry." + "see ZOOKEEPER-2836"); } } } catch (IOException e) { if (shutdown) { break; } LOG.error("Exception while listening", e); numRetries++; try { ss.close(); Thread.sleep(1000); } catch (IOException ie) { LOG.error("Error closing server socket", ie); } catch (InterruptedException ie) { LOG.error("Interrupted while sleeping. " + "Ignoring exception", ie); } closeSocket(client); } } LOG.info("Leaving listener"); if (!shutdown) { LOG.error("As I'm leaving the listener thread, " + "I won't be able to participate in leader " + "election any longer: " + self.getElectionAddress()); } else if (ss != null) { try { ss.close(); } catch (IOException ie) { LOG.debug("Error closing server socket", ie); } } }
Source:
public BridgeFactory(ServiceManager serviceManager) { annotationBasedProviders = new HashSet<BridgeProvider>(5); annotationBasedProviders.add( new CalendarBridgeProvider() ); annotationBasedProviders.add( new DateBridgeProvider() ); annotationBasedProviders.add( new NumericBridgeProvider() ); annotationBasedProviders.add( new SpatialBridgeProvider() ); annotationBasedProviders.add( new TikaBridgeProvider() ); ClassLoaderService classLoaderService = serviceManager.requestService( ClassLoaderService.class ); regularProviders = classLoaderService.loadJavaServices( BridgeProvider.class ); regularProviders.add( new EnumBridgeProvider() ); regularProviders.add( new DefaultBridgeProvider(serviceManager) ); }

Target:
public BridgeFactory(ServiceManager serviceManager) { annotationBasedProviders = new HashSet<BridgeProvider>(5); annotationBasedProviders.add( new CalendarBridgeProvider() ); annotationBasedProviders.add( new DateBridgeProvider() ); annotationBasedProviders.add( new NumericBridgeProvider() ); annotationBasedProviders.add( new SpatialBridgeProvider() ); annotationBasedProviders.add( new TikaBridgeProvider() ); ClassLoaderService classLoaderService = serviceManager.requestService( ClassLoaderService.class ); try { regularProviders = classLoaderService.loadJavaServices( BridgeProvider.class ); regularProviders.add( new EnumBridgeProvider() ); regularProviders.add( new BasicJDKTypesBridgeProvider( serviceManager ) ); } finally { serviceManager.releaseService( ClassLoaderService.class ); } }
Source:
private static void assignTagsFromJson(ReaderPost post, JSONObject jsonTags) { if (jsonTags == null) { return; } Iterator<String> it = jsonTags.keys(); if (!it.hasNext()) { return; } String mostPopularTag = null; String nextMostPopularTag = null; int popularCount = 0; while (it.hasNext()) { JSONObject jsonThisTag = jsonTags.optJSONObject(it.next()); int postCount = jsonThisTag.optInt("post_count"); if (postCount > popularCount) { nextMostPopularTag = mostPopularTag; mostPopularTag = JSONUtils.getStringDecoded(jsonThisTag, "display_name"); popularCount = postCount; } } if (!post.hasPrimaryTag()) { post.setPrimaryTag(mostPopularTag); } post.setSecondaryTag(nextMostPopularTag); }

Target:
private static void assignTagsFromJson(ReaderPost post, JSONObject jsonTags) { if (jsonTags == null) { return; } Iterator<String> it = jsonTags.keys(); if (!it.hasNext()) { return; } String mostPopularTag = null; String nextMostPopularTag = null; int popularCount = 0; while (it.hasNext()) { JSONObject jsonThisTag = jsonTags.optJSONObject(it.next()); int postCount = jsonThisTag.optInt("post_count"); if (postCount > popularCount) { nextMostPopularTag = mostPopularTag; mostPopularTag = JSONUtils.getStringDecoded(jsonThisTag, "slug"); popularCount = postCount; } } if (!post.hasPrimaryTag()) { post.setPrimaryTag(mostPopularTag); } post.setSecondaryTag(nextMostPopularTag); }
Source:
public Map<String, String> getTags() { return tags; }

Target:
public Map<String, String> getTags() { return Collections.unmodifiableMap(tags); }
Source:
public static <T> Predicate<Location> isDescendantOf(final Location ancestor) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { Location contender = input; while (contender != null) { if (Objects.equal(contender, ancestor)) { return true; } contender = contender.getParent(); } return false; } }; }

Target:
public static <T> Predicate<Location> isDescendantOf(final Location ancestor) { return new Predicate<Location>() { @Override public boolean apply(@Nullable Location input) { Location contenderAncestor = (input == null) ? input : input.getParent(); while (contenderAncestor != null) { if (Objects.equal(contenderAncestor, ancestor)) { return true; } contenderAncestor = contenderAncestor.getParent(); } return false; } }; }
Source:
public <T extends Annotation> T getConfig(Class<T> type) { List<T> configs = new ArrayList<>(); T annotation = scanner.getAnnotation(getTargetTestClass(), type); if (annotation != null) { configs.add(annotation); } apply("getAnnontation", BACKWARD, holder -> { T hAnnotation = scanner.getAnnotation(holder.type, type); if (hAnnotation != null) { configs.add(hAnnotation); } }); return Defaults.of(type, configs); }

Target:
public <T extends Annotation> T getConfig(Class<T> type) { List<T> configs = new ArrayList<>(); T annotation = scanner.getAnnotation(getTargetTestClass(), type); if (annotation != null) { configs.add(annotation); } apply("getAnnotation", BACKWARD, holder -> { T hAnnotation = scanner.getAnnotation(holder.type, type); if (hAnnotation != null) { configs.add(hAnnotation); } }); return Defaults.of(type, configs); }
Source:
public void preProcessModule(Module module) { module.addListener(new ApplicationListener<ApplicationPreparedEvent>() { @Override public void onApplicationEvent(ApplicationPreparedEvent event) { ZooKeeperConnection bean = getApplicationContext().getBean(ZooKeeperConnection.class); ConfigurableListableBeanFactory moduleBeanFactory = event.getApplicationContext().getBeanFactory(); moduleBeanFactory.registerSingleton(XD_ZOOKEEPER_CONNECTION, bean.getClient()); } }); }

Target:
public void preProcessModule(Module module) { module.addListener(new ApplicationListener<ApplicationPreparedEvent>() { @Override public void onApplicationEvent(ApplicationPreparedEvent event) { ZooKeeperConnection bean = getApplicationContext().getBean(ZooKeeperConnection.class); ConfigurableListableBeanFactory moduleBeanFactory = event.getApplicationContext().getBeanFactory(); moduleBeanFactory.registerSingleton(XD_ZOOKEEPER_CLIENT, bean.getClient()); } }); }
Source:
E parseEntry(Row<GenericTableSchema> row, Class<E> clazz) throws IllegalArgumentException { if (!clazz.isAssignableFrom(LogicalSwitch.class)) throw new IllegalArgumentException("wrong entry type " + clazz + " for table " + this.getClass()); return (E)LogicalSwitch.apply(parseUuid(row), parseName(row), parseTunnelKey(row), parseDescription(row)); }

Target:
E parseEntry(Row<GenericTableSchema> row, Class<E> clazz) throws IllegalArgumentException { ensureOutputClass(clazz); return (E)LogicalSwitch.apply(parseUuid(row), parseName(row), parseTunnelKey(row), parseDescription(row)); }
Source:
public void testSessionTokenIdentifierRoundTrip() throws Throwable { Text renewer = new Text("yarn"); SessionTokenIdentifier id = new SessionTokenIdentifier( SESSION_TOKEN_KIND, new Text(), renewer, landsatUri, new MarshalledCredentials("a", "b", "c"), new EncryptionSecrets(), ""); SessionTokenIdentifier result = S3ATestUtils.roundTrip(id, null); String ids = id.toString(); assertEquals("URI in " + ids, id.getUri(), result.getUri()); assertEquals("credentials in " + ids, id.getMarshalledCredentials(), result.getMarshalledCredentials()); assertEquals(renewer, id.getRenewer()); }

Target:
public void testSessionTokenIdentifierRoundTrip() throws Throwable { Text renewer = new Text("yarn"); SessionTokenIdentifier id = new SessionTokenIdentifier( SESSION_TOKEN_KIND, new Text(), renewer, landsatUri, new MarshalledCredentials("a", "b", "c"), new EncryptionSecrets(), ""); SessionTokenIdentifier result = S3ATestUtils.roundTrip(id, null); String ids = id.toString(); assertEquals("URI in " + ids, id.getUri(), result.getUri()); assertEquals("credentials in " + ids, id.getMarshalledCredentials(), result.getMarshalledCredentials()); assertEquals("renewer in " + ids, renewer, id.getRenewer()); }
Source:
public void testCompareToOfTagClass() { final SuppressionCommentFilter filter1 = new SuppressionCommentFilter(); final List<Comparable<Object>> tags1 = getTagsAfterExecution(filter1, "filename", " final Comparable<Object> tag1 = tags1.get(0); final Comparable<Object> tag2 = tags1.get(1); final SuppressionCommentFilter filter2 = new SuppressionCommentFilter(); final List<Comparable<Object>> tags2 = getTagsAfterExecution(filter2, "filename", " final Comparable<Object> tag3 = tags2.get(0); final SuppressionCommentFilter filter3 = new SuppressionCommentFilter(); final List<Comparable<Object>> tags3 = getTagsAfterExecution(filter3, "filename", " final Comparable<Object> tag4 = tags3.get(0); assertTrue("Invalid comparing result", tag1.compareTo(tag2) < 0); assertTrue("Invalid comparing result", tag2.compareTo(tag1) > 0); assertTrue("Invalid comparing result", tag1.compareTo(tag3) < 0); assertTrue("Invalid comparing result", tag3.compareTo(tag1) > 0); assertEquals("Invalid comparing result", 0, tag1.compareTo(tag4)); }

Target:
public void testCompareToOfTagClass() { final List<Comparable<Object>> tags1 = getTagsAfterExecutionOnDefaultFilter(" final Comparable<Object> tag1 = tags1.get(0); final Comparable<Object> tag2 = tags1.get(1); final List<Comparable<Object>> tags2 = getTagsAfterExecutionOnDefaultFilter(" final Comparable<Object> tag3 = tags2.get(0); final List<Comparable<Object>> tags3 = getTagsAfterExecutionOnDefaultFilter(" final Comparable<Object> tag4 = tags3.get(0); assertTrue("Invalid comparing result", tag1.compareTo(tag2) < 0); assertTrue("Invalid comparing result", tag2.compareTo(tag1) > 0); assertTrue("Invalid comparing result", tag1.compareTo(tag3) < 0); assertTrue("Invalid comparing result", tag3.compareTo(tag1) > 0); assertEquals("Invalid comparing result", 0, tag1.compareTo(tag4)); }
Source:
protected void populateRoles(List<Role> roles){ Role selectedRole = null; for (Role role : roles) { if (role.getId() != null) { if (role.getId().equals(ApplicationGuids.quotaConsumer.asGuid())) { roles.remove(role); } if (role.getId().equals(ApplicationGuids.engineUser.asGuid())) { selectedRole = role; } } } Collections.sort(roles, new Comparator<Role>() { @Override public int compare(Role left, Role right) { return left.getname().compareTo(right.getname()); } }); getRole().setItems(roles); if (selectedRole != null) { getRole().setSelectedItem(selectedRole); } else if (roles.size() > 0){ getRole().setSelectedItem(roles.get(0)); } }

Target:
protected void populateRoles(List<Role> roles){ Role selectedRole = null; for (Role role : roles) { if (role.getId() != null) { if (role.getId().equals(ApplicationGuids.quotaConsumer.asGuid())) { roles.remove(role); } if (role.getId().equals(ApplicationGuids.engineUser.asGuid())) { selectedRole = role; } } } Collections.sort(roles, new Linq.RoleNameComparer()); getRole().setItems(roles); if (selectedRole != null) { getRole().setSelectedItem(selectedRole); } else if (roles.size() > 0){ getRole().setSelectedItem(roles.get(0)); } }
Source:
public Optional<DateTime> getQuestionsLastViewed(Long accountId) { final GetItemRequest getRequest = new GetItemRequest(); getRequest.addKeyEntry(ACCOUNT_ID_ATTRIBUTE_NAME, new AttributeValue().withN(accountId.toString())); getRequest.setAttributesToGet(Lists.newArrayList(QUESTIONS_LAST_VIEWED_ATTRIBUTE_NAME)); getRequest.setTableName(tableName); final GetItemResult result = dynamoDB.getItem(getRequest); final Map<String, AttributeValue> attributes = result.getItem(); if (attributes != null && attributes.containsKey(QUESTIONS_LAST_VIEWED_ATTRIBUTE_NAME)) { final AttributeValue attribute = attributes.get(QUESTIONS_LAST_VIEWED_ATTRIBUTE_NAME); final String value = attribute.getN(); final long lastViewedMillis = Long.parseLong(value, 10); return Optional.of(new DateTime(lastViewedMillis, DateTimeZone.UTC)); } else { return Optional.absent(); } }

Target:
public Optional<DateTime> getQuestionsLastViewed(Long accountId) { final GetItemRequest getRequest = new GetItemRequest(); getRequest.addKeyEntry(ACCOUNT_ID_ATTRIBUTE_NAME, new AttributeValue().withN(accountId.toString())); getRequest.setAttributesToGet(Lists.newArrayList(QUESTIONS_LAST_VIEWED_ATTRIBUTE_NAME)); getRequest.setTableName(tableName); final GetItemResult result = dynamoDB.getItem(getRequest); final Map<String, AttributeValue> attributes = result.getItem(); if (attributes != null && attributes.containsKey(QUESTIONS_LAST_VIEWED_ATTRIBUTE_NAME)) { final AttributeValue attribute = attributes.get(QUESTIONS_LAST_VIEWED_ATTRIBUTE_NAME); final String value = attribute.getN(); final long lastViewedMillis = Long.parseLong(value, 10); return Optional.of(new DateTime(lastViewedMillis, DateTimeZone.UTC)); } return Optional.absent(); }
Source:
public void testSubsystem() throws OperationFailedException { PathAddress address = PathAddress.pathAddress(SUBSYSTEM, TEST_SUBSYSTEM); ModelNode result = readFeature(address); ModelNode feature = result.require(FEATURE); Assert.assertEquals(serializeAddress(address), feature.require(NAME).asString()); Map<String, ModelNode> params = extractParamsToMap(feature); Assert.assertEquals(2, params.size()); assertFeatureIdParam(SUBSYSTEM, TEST_SUBSYSTEM, params); assertParamWithDefault(EXTENSION, TEST_EXTENSION, params); ModelNode provides = feature.require("provides"); Assert.assertEquals(1, provides.asList().size()); Assert.assertEquals("subsystem-capability", provides.get(0).asString()); Assert.assertEquals(1, feature.require("refs").asList().size()); Assert.assertEquals("extension", feature.require("refs").require(0).require(FEATURE).asString()); Assert.assertTrue(feature.require("refs").require(0).require(INCLUDE).asBoolean()); ModelNode packages = feature.require("packages"); Assert.assertEquals(1, packages.asList().size()); Assert.assertEquals(TEST_EXTENSION + ".main", packages.get(0).require("package").asString()); }

Target:
public void testSubsystem() throws OperationFailedException { PathAddress address = PathAddress.pathAddress(SUBSYSTEM, TEST_SUBSYSTEM); ModelNode result = readFeatureDescription(address); ModelNode feature = result.require(FEATURE); Assert.assertEquals(serializeAddress(address), feature.require(NAME).asString()); Map<String, ModelNode> params = extractParamsToMap(feature); Assert.assertEquals(2, params.size()); assertFeatureIdParam(SUBSYSTEM, TEST_SUBSYSTEM, params); assertParamWithDefault(EXTENSION, TEST_EXTENSION, params); ModelNode provides = feature.require(PROVIDES); Assert.assertEquals(1, provides.asList().size()); Assert.assertEquals("subsystem-capability", provides.get(0).asString()); ModelNode refs = feature.require(REFS); Assert.assertEquals(1, refs.asList().size()); Assert.assertEquals("extension", refs.require(0).require(FEATURE).asString()); Assert.assertTrue(refs.require(0).require(INCLUDE).asBoolean()); ModelNode packages = feature.require(PACKAGES); Assert.assertEquals(1, packages.asList().size()); Assert.assertEquals(TEST_EXTENSION + ".main", packages.get(0).require(PACKAGE).asString()); }
Source:
public int getSize(){ int debugSize = getDebugInfo().getSize(); Iterator<? extends Instruction> iter = getInstructions().iterator(); while (iter.hasNext()){ iter.next(); } int lastOffset = ((VariableSizeLookaheadIterator)iter).getReaderOffset(); for (DexBackedTryBlock tryBlock: getTryBlocks()){ Iterator<? extends DexBackedExceptionHandler> tryHandlerIter = tryBlock.getExceptionHandlers().iterator(); while (tryHandlerIter.hasNext()){ tryHandlerIter.next(); } lastOffset = ((VariableSizeListIterator)tryHandlerIter).getReaderOffset(); } return debugSize + (lastOffset - codeOffset); }

Target:
public int getSize() { int debugSize = getDebugInfo().getSize(); int lastOffset = dexFile.readSmallUint(codeOffset + CodeItem.INSTRUCTION_COUNT_OFFSET) * 2; for (DexBackedTryBlock tryBlock: getTryBlocks()) { Iterator<? extends DexBackedExceptionHandler> tryHandlerIter = tryBlock.getExceptionHandlers().iterator(); while (tryHandlerIter.hasNext()) { tryHandlerIter.next(); } lastOffset = ((VariableSizeListIterator)tryHandlerIter).getReaderOffset(); } return debugSize + (lastOffset - codeOffset); }
Source:
protected int insertDbDataInQueue(PreparedStatement preparedStatement) throws SQLException, InterruptedException { int resultCount = 0; preparedStatement.setFetchSize(getFetchSize()); ResultSet result = preparedStatement.executeQuery(); if (result.next()) { do { T obj = getTuple(result); while (execute && !emitQueue.offer(obj)) { Thread.sleep(DEFAULT_SLEEP_TIME); } if (isPollerPartition && rebaseOffset) { if (prevKey == null) { prevKey = extractKey(result); } else if (this.fetchedKeyAndOffset.get() == null) { Object nextKey = extractKey(result); if (!nextKey.equals(prevKey)) { fetchedKeyAndOffset.set(new MutablePair<>(prevKey, lastOffset + resultCount)); } } } resultCount++; } while (execute && result.next()); result.close(); } preparedStatement.close(); return resultCount; }

Target:
protected int insertDbDataInQueue(PreparedStatement preparedStatement) throws SQLException, InterruptedException { int resultCount = 0; preparedStatement.setFetchSize(getFetchSize()); ResultSet result = preparedStatement.executeQuery(); while (execute && result.next()) { T obj = getTuple(result); if (obj == null) { continue; } while (execute && !emitQueue.offer(obj)) { Thread.sleep(DEFAULT_SLEEP_TIME); } if (isPollerPartition && rebaseOffset) { if (prevKey == null) { prevKey = extractKey(result); } else if (this.fetchedKeyAndOffset.get() == null) { Object nextKey = extractKey(result); if (!nextKey.equals(prevKey)) { fetchedKeyAndOffset.set(new MutablePair<>(prevKey, lastOffset + resultCount)); } } } resultCount++; } result.close(); preparedStatement.close(); return resultCount; }
Source:
public String getSemanticObjectLabel(Object object) { ResourceAttachmentChange resourceAttachmentChange = (ResourceAttachmentChange)object; final Match match = resourceAttachmentChange.getMatch(); String value = itemDelegator.getText(match.getLeft()); if (isNullOrEmpty(value)) { value = itemDelegator.getText(match.getRight()); } if (isNullOrEmpty(value)) { value = itemDelegator.getText(match.getOrigin()); } if (isNullOrEmpty(value)) { value = super.getText(object); } return value; }

Target:
public String getSemanticObjectLabel(Object object) { final ResourceAttachmentChange resourceAttachmentChange = (ResourceAttachmentChange)object; return doGetSemanticObjectLabel(resourceAttachmentChange, object); }
Source:
public static String getFileMimeType(final File file) throws IOException { if (file != null) { final Tika tika = new Tika(); return tika.detect(file.getInputStream()); } return null; }

Target:
public static String getFileMimeType(final File file) { if (file != null) { try { final Tika tika = new Tika(); return tika.detect(file.getInputStream()); } catch (IOException ex) { LOG.error("Invalid file, name " + file.getName(), ex); } } return null; }
Source:
public static void main(String[] args) { junit.textui.TestRunner.run(GDI32Test.class); }

Target:
public static void main(String[] args) { JUnitCore jUnitCore = new JUnitCore(); jUnitCore.run(GDI32UtilTest.class); }
Source:
public static void setEnv(Map<String, String> newVariables) { Map<String, String> newenv = new HashMap<>(); newenv.putAll(System.getenv()); newenv.putAll(newVariables); try { Class<?> processEnvironmentClass = Class.forName(PROCESS_ENVIRONMENT); Field theEnvironmentField = processEnvironmentClass.getDeclaredField(THE_ENVIRONMENT_FILED); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField(THE_CASE_INSENSITIVE_ENVIRONMENT); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); } catch (NoSuchFieldException e) { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); Arrays.asList(classes).stream().filter(cl -> COLLECTIONS_UNMODIFIABLE_MAP.equals(cl.getName())).forEach( (cl) -> { try { Field field = cl.getDeclaredField(FIELD_M); field.setAccessible(true); Object obj = field.get(env); Map<String, String> map = (Map<String, String>) obj; map.clear(); map.putAll(newenv); } catch (IllegalAccessException | NoSuchFieldException ex) { logger.error("Unable to set environment variable via unmodifiable map", ex); } } ); } catch (ClassNotFoundException | IllegalAccessException e) { logger.error("Unable to set environment variable", e); } }

Target:
public static void setEnv(Map<String, String> newVariables) { Map<String, String> newenv = new HashMap<>(); newenv.putAll(System.getenv()); newenv.putAll(newVariables); try { Class<?> processEnvironmentClass = Class.forName(PROCESS_ENVIRONMENT); Field theEnvironmentField = processEnvironmentClass.getDeclaredField(THE_ENVIRONMENT_FILED); theEnvironmentField.setAccessible(true); Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null); env.putAll(newenv); Field theCaseInsensitiveEnvironmentField = processEnvironmentClass .getDeclaredField(THE_CASE_INSENSITIVE_ENVIRONMENT); theCaseInsensitiveEnvironmentField.setAccessible(true); Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); cienv.putAll(newenv); } catch (NoSuchFieldException e) { Class[] classes = Collections.class.getDeclaredClasses(); Map<String, String> env = System.getenv(); Arrays.asList(classes).stream().filter(cl -> COLLECTIONS_UNMODIFIABLE_MAP.equals(cl.getName())).forEach( (cl) -> { try { Field field = cl.getDeclaredField(FIELD_M); field.setAccessible(true); Map<String, String> map = (Map<String, String>) field.get(env); map.clear(); map.putAll(newenv); } catch (IllegalAccessException | NoSuchFieldException ex) { logger.error("Unable to set environment variable via unmodifiable map", ex); } } ); } catch (ClassNotFoundException | IllegalAccessException e) { logger.error("Unable to set environment variable", e); } }
Source:
public boolean forgetPortMapping(String publicIpId, int publicPort) { PortMapping old; synchronized (mutex) { old = mappings.remove(makeKey(publicIpId, publicPort)); emitAssociationDeletedEvent(associationMetadataFromPortMapping(old)); log.debug("cleared port mapping for "+publicIpId+":"+publicPort+" - "+old); } if (old != null) onChanged(); return (old != null); }

Target:
public boolean forgetPortMapping(String publicIpId, int publicPort) { PortMapping old; synchronized (mutex) { old = mappings.remove(makeKey(publicIpId, publicPort)); if (old != null) { emitAssociationDeletedEvent(associationMetadataFromPortMapping(old)); } log.debug("cleared port mapping for "+publicIpId+":"+publicPort+" - "+old); } if (old != null) onChanged(); return (old != null); }
Source:
public List<String> getAvailableCatalogs() throws IllegalArgumentException { try { return OPACConfig.getCatalogs(); } catch (IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw new IllegalArgumentException("Error: no supported OPACs found in configuration file!"); } }

Target:
public List<String> getAvailableCatalogs() { try { return OPACConfig.getCatalogs(); } catch (IllegalArgumentException e) { logger.error(e.getLocalizedMessage()); throw new IllegalArgumentException("Error: no supported OPACs found in configuration file!"); } }