auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean canBeCraftedBy(ItemStack stack) { if (stack == null) return false; return input.stackSize <= stack.stackSize && Utils.areSame(stack, input); }

Target:
public boolean canBeCraftedBy(ItemStack stack) { if (stack.isEmpty()) return false; return input.getCount() <= stack.getCount() && Utils.areSame(stack, input); }
Source:
public Account getAccountByName(String accountName) { Account primaryResult = primaryAccountService.getAccountByName(accountName); Account secondaryResult = secondaryAccountService.getAccountByName(accountName); if (++getAccountRequestCount % 100 < config.samplingPercentageForGetAccountConsistencyCheck && primaryResult != null && !primaryResult.equals(secondaryResult)) { logger.warn("Inconsistency detected between primary and secondary for accountName ={}", accountName); accountServiceMetrics.getAccountDataInconsistencyCount.inc(); } return primaryResult; }

Target:
public Account getAccountByName(String accountName) { Account primaryResult = primaryAccountService.getAccountByName(accountName); if (shouldCompare()) { Account secondaryResult = secondaryAccountService.getAccountByName(accountName); if (primaryResult != null && !primaryResult.equals(secondaryResult)) { logger.warn("Inconsistency detected between primary and secondary for accountName ={}", accountName); accountServiceMetrics.accountDataInconsistencyCount.inc(); } } return primaryResult; }
Source:
protected void verifyCannotAccess(String... params) throws Exception { try { Action c = gaeSimulation.getActionObject(uri, params); ActionResult result = c.executeAndPostProcess(); String classNameOfRedirectResult = RedirectResult.class.getName(); assertEquals(classNameOfRedirectResult, result.getClass().getName()); } catch (Exception e) { ignoreExpectedException(); } ; }

Target:
protected void verifyCannotAccess(String... params) throws Exception { try { Action c = gaeSimulation.getActionObject(uri, params); ActionResult result = c.executeAndPostProcess(); String classNameOfRedirectResult = RedirectResult.class.getName(); assertEquals(classNameOfRedirectResult, result.getClass().getName()); } catch (Exception e) { ignoreExpectedException(); } }
Source:
public boolean synchronize(DocumentFile event) throws Exception { OutputStream fout = null; try { fout = event.getPath().out(); xstream.toXML(event.getBody(), fout); return true; } catch (IllegalStateException e) { if (LOGGER.isLoggable(java.util.logging.Level.SEVERE)) LOGGER.severe(e.getLocalizedMessage()); throw e; } finally { IOUtils.closeQuietly(fout); } }

Target:
public boolean synchronize(DocumentFile event) throws Exception { try (OutputStream fout = event.getPath().out()) { xstream.toXML(event.getBody(), fout); return true; } catch (IllegalStateException e) { if (LOGGER.isLoggable(java.util.logging.Level.SEVERE)) LOGGER.severe(e.getLocalizedMessage()); throw e; } }
Source:
public RegistryResponseType processRequest(AdhocQueryRequest msg, AssertionType assertion) { LOG.debug("Running through AdapterDeferredResponseOptionProxyWebServiceSecuredImpl"); RegistryResponseType response = null; try { if (msg == null) { throw new IllegalArgumentException("Request Message must be provided"); } response = (RegistryResponseType) invokeClientPort(getRequest(msg), assertion); } catch (final Exception ex) { response = AdapterResponseHelper.createRegistryResponseTypeWithXdsQueryFailure(ERROR_MSG); throw new ErrorEventException(ex, response, ERROR_MSG); } return response; }

Target:
public RegistryResponseType processRequest(AdhocQueryRequest msg, AssertionType assertion) { LOG.debug("Running through AdapterDeferredResponseOptionProxyWebServiceSecuredImpl"); RegistryResponseType response = null; try { if (msg == null) { throw new IllegalArgumentException("Request Message must be provided"); } response = (RegistryResponseType) invokeClientPort(getRequest(msg), assertion); } catch (final Exception ex) { response = AdapterResponseHelper.createFailureWithMessage(ERROR_MSG); throw new ErrorEventException(ex, response, ERROR_MSG); } return response; }
Source:
public void sendRequest(NetworkRequest request) throws InterruptedException { DataInputStream stream = new DataInputStream(request.getInputStream()); try { stream.readLong(); } catch (IOException e) { throw new InterruptedException("stream read error." + e); } requestQueue.put(request); }

Target:
public void sendRequest(NetworkRequest request) throws InterruptedException { DataInputStream stream = new DataInputStream(request.getInputStream()); try { stream.readLong(); } catch (IOException e) { throw new IllegalStateException("stream read error." + e); } requestQueue.put(request); }
Source:
public boolean cancelOrder(String s) { throw new UnsupportedOperationException("Orders Api Unnavailable at this time"); }

Target:
public boolean cancelOrder(String s) { throw new NotAvailableFromExchangeException(); }
Source:
public void uncaughtException(Thread thread, Throwable ex) { try { String excInfo = ex.getMessage(); Tracker tracker = getTracker(); TrackHelper.track(mTrackMe).exception(ex).description(excInfo).fatal(true).with(tracker); tracker.setOffline(); tracker.dispatchBlocking(); } catch (Exception e) { Timber.tag(TAG).e(e, "Couldn't track uncaught exception"); } finally { if (getDefaultExceptionHandler() != null && getDefaultExceptionHandler() != this) { getDefaultExceptionHandler().uncaughtException(thread, ex); } } }

Target:
public void uncaughtException(Thread thread, Throwable ex) { try { String excInfo = ex.getMessage(); Tracker tracker = getTracker(); tracker.setDispatchMode(DispatchMode.EXCEPTION); TrackHelper.track(mTrackMe).exception(ex).description(excInfo).fatal(true).with(tracker); tracker.dispatchBlocking(); } catch (Exception e) { Timber.tag(TAG).e(e, "Couldn't track uncaught exception"); } finally { if (getDefaultExceptionHandler() != null && getDefaultExceptionHandler() != this) { getDefaultExceptionHandler().uncaughtException(thread, ex); } } }
Source:
public Map<?, ListenableFuture<Void>> execute(final String group, final int count, final Template template, final Set<NodeMetadata> goodNodes, final Map<NodeMetadata, Exception> badNodes, final Multimap<NodeMetadata, CustomizationResponse> customizationResponses) { final DimensionDataCloudControlTemplateOptions templateOptions = template.getOptions() .as(DimensionDataCloudControlTemplateOptions.class); String networkDomainName = firstNonNull(templateOptions.getNetworkDomainName(), DEFAULT_NETWORK_DOMAIN_NAME); String vlanName = firstNonNull(templateOptions.getVlanName(), DEFAULT_VLAN_NAME); String datacenterId = template.getLocation().getId(); String networkDomainId = tryCreateOrGetExistingNetworkDomainId(datacenterId, networkDomainName); templateOptions.networkDomainId(networkDomainId); templateOptions.networkDomainName(networkDomainName); String vlanId = tryCreateOrGetExistingVlanId(templateOptions.getNetworkDomainId(), vlanName, templateOptions); templateOptions.vlanId(vlanId); templateOptions.vlanName(vlanName); return super.execute(group, count, template, goodNodes, badNodes, customizationResponses); }

Target:
public Map<?, ListenableFuture<Void>> execute(final String group, final int count, final Template template, final Set<NodeMetadata> goodNodes, final Map<NodeMetadata, Exception> badNodes, final Multimap<NodeMetadata, CustomizationResponse> customizationResponses) { final DimensionDataCloudControlTemplateOptions templateOptions = template.getOptions() .as(DimensionDataCloudControlTemplateOptions.class); String networkDomainName = firstNonNull(templateOptions.getNetworkDomainName(), DEFAULT_NETWORK_DOMAIN_NAME); String vlanName = firstNonNull( templateOptions.getNetworks().isEmpty() ? null : templateOptions.getNetworks().iterator().next(), DEFAULT_VLAN_NAME); templateOptions.networkDomainName(networkDomainName); String networkDomainId = tryCreateOrGetExistingNetworkDomainId(template.getLocation().getId(), networkDomainName); String vlanId = tryCreateOrGetExistingVlanId(networkDomainId, vlanName, templateOptions); templateOptions.networks(vlanName); return super .execute(group, count, new TemplateWithNetworkIds(template, networkDomainId, vlanId), goodNodes, badNodes, customizationResponses); }
Source:
public void testFindDonorsWithDonationIdentificationNumber_shouldFindDonorByDonationIdentificationNumber() { String donationIdentificationNumber = "1000001"; Donor donor = aDonor().withId(UUID.randomUUID()).build(); List<DonorSummaryViewModel> donorViewModels = Arrays.asList(aDonorSummaryViewModel().withId(UUID.randomUUID()).build()); when(donorRepository.findDonorByDonationIdentificationNumber(donationIdentificationNumber)).thenReturn(donor); when(donorViewModelFactory.createDonorSummaryViewModels(Arrays.asList(donor))).thenReturn(donorViewModels); when(generalConfigAccessorService.getBooleanValue(GeneralConfigConstants.DONOR_REGISTRATION_OPEN_BATCH_REQUIRED)).thenReturn(false); Map<String, Object> result = donorController.findDonors("", "", null, false, donationIdentificationNumber); assertThat((List<DonorSummaryViewModel>) result.get("donors"), equalTo(donorViewModels)); }

Target:
public void testFindDonorsWithDonationIdentificationNumber_shouldFindDonorByDonationIdentificationNumber() { String donationIdentificationNumber = "1000001"; UUID donorId = UUID.randomUUID(); Donor donor = aDonor().withId(donorId).build(); List<DonorSummaryViewModel> donorViewModels = Arrays.asList(aDonorSummaryViewModel().withId(donorId).build()); when(donorRepository.findDonorByDonationIdentificationNumber(donationIdentificationNumber)).thenReturn(donor); when(donorViewModelFactory.createDonorSummaryViewModels(Arrays.asList(donor))).thenReturn(donorViewModels); when(generalConfigAccessorService.getBooleanValue(GeneralConfigConstants.DONOR_REGISTRATION_OPEN_BATCH_REQUIRED)).thenReturn(false); Map<String, Object> result = donorController.findDonors("", "", null, false, donationIdentificationNumber); assertThat((List<DonorSummaryViewModel>) result.get("donors"), equalTo(donorViewModels)); }
Source:
public final BeanMetaData<T> getCurrentBeanMetaData() { if ( currentBeanType != null && currentBeanMetaData == null ) { currentBeanMetaData = beanMetaDataManager.getBeanMetaData( currentBeanType ); } return currentBeanMetaData; }

Target:
public final BeanMetaData<T> getCurrentBeanMetaData() { return currentBeanMetaData; }
Source:
public Encounter createEncounter(String configName, DateTime encounterDatetime, String encounterType, String locationName, String patientUuid, String providerUuid, String visitUuid, Map<String, String> observations) { Location location = getLocationByName(configName, locationName); Patient patient = patientService.getPatientByUuid(configName, patientUuid); Provider provider = providerService.getProviderByUuid(configName, providerUuid); Visit visit = visitService.getVisitByUuid(configName, visitUuid); List<Observation> observationList = MapUtils.isNotEmpty(observations) ? convertObservationMapToList(observations, encounterDatetime) : null; EncounterType type = new EncounterType(encounterType); Encounter encounter = new Encounter(location, type, encounterDatetime.toDate(), patient, visit, Collections.singletonList(provider.getPerson()), observationList); return encounterService.createEncounter(configName, encounter); }

Target:
public Encounter createEncounter(String configName, DateTime encounterDatetime, String encounterType, String locationName, String patientUuid, String providerUuid, String visitUuid, Map<String, String> observations) { Location location = getLocationByName(configName, locationName); Patient patient = patientService.getPatientByUuid(configName, patientUuid); Provider provider = providerService.getProviderByUuid(configName, providerUuid); Visit visit = null; if (StringUtils.isNotEmpty(visitUuid)) { visit = visitService.getVisitByUuid(configName, visitUuid); } List<Observation> observationList = MapUtils.isNotEmpty(observations) ? convertObservationMapToList(observations, encounterDatetime) : null; EncounterType type = new EncounterType(encounterType); Encounter encounter = new Encounter(location, type, encounterDatetime.toDate(), patient, visit, Collections.singletonList(provider.getPerson()), observationList); return encounterService.createEncounter(configName, encounter); }
Source:
public static Future<?> deleteFeedMediaOfItem(final Context context, final long mediaId) { if (UserPreferences.shouldDeleteRemoveFromQueue()) { DBWriter.removeQueueItem(context, DBReader.getFeedMedia(mediaId).getItem(), false); } return doDeleteFeedMediaOfItem(context, mediaId); }

Target:
public static Future<?> deleteFeedMediaOfItem(final Context context, final long mediaId) { Future res = doDeleteFeedMediaOfItem(context, mediaId); if (UserPreferences.shouldDeleteRemoveFromQueue()) { DBWriter.removeQueueItem(context, DBReader.getFeedMedia(mediaId).getItem(), false); } return res; }
Source:
private Object nullInputEvaluator(final Collection<VariableReferenceExpression> nullVariables, Expression expression) { Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes( session, metadata, sqlParser, types, expression, emptyList(), WarningCollector.NOOP); return ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes) .optimize(symbol -> nullVariables.stream() .map(VariableReferenceExpression::getName) .collect(toImmutableSet()) .contains(symbol.getName()) ? null : symbol.toSymbolReference()); }

Target:
private Object nullInputEvaluator(final Collection<VariableReferenceExpression> nullVariables, Expression expression) { Set<String> nullVariableNames = nullVariables.stream() .map(VariableReferenceExpression::getName) .collect(toImmutableSet()); Map<NodeRef<Expression>, Type> expressionTypes = getExpressionTypes( session, metadata, sqlParser, types, expression, emptyList(), WarningCollector.NOOP); return ExpressionInterpreter.expressionOptimizer(expression, metadata, session, expressionTypes) .optimize(symbol -> nullVariableNames.contains(symbol.getName()) ? null : symbol.toSymbolReference()); }
Source:
public IarParser() { super(Messages._Warnings_iar_ParserName(), Messages._Warnings_iar_LinkName(), Messages._Warnings_iar_TrendName(), IAR_WARNING_PATTERN); }

Target:
public IarParser() { super(Messages._Warnings_iar_ParserName(), Messages._Warnings_iar_LinkName(), Messages._Warnings_iar_TrendName(), IAR_WARNING_PATTERN, true); }
Source:
public void setup() throws IOException, AuthenticationException { OzoneConfiguration conf = new OzoneConfiguration(); conf.setInt( ScmConfigKeys.OZONE_DATANODE_MAX_PIPELINE_ENGAGEMENT, 1000); storageDir = GenericTestUtils.getTempPath( TestDeadNodeHandler.class.getSimpleName() + UUID.randomUUID()); conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, storageDir); eventQueue = new EventQueue(); scm = HddsTestUtils.getScm(conf); nodeManager = (SCMNodeManager) scm.getScmNodeManager(); SCMPipelineManager manager = (SCMPipelineManager)scm.getPipelineManager(); PipelineProvider mockRatisProvider = new MockRatisPipelineProvider(nodeManager, manager.getStateManager(), conf); manager.setPipelineProvider(HddsProtos.ReplicationType.RATIS, mockRatisProvider); containerManager = scm.getContainerManager(); deadNodeHandler = new DeadNodeHandler(nodeManager, Mockito.mock(PipelineManager.class), containerManager); eventQueue.addHandler(SCMEvents.DEAD_NODE, deadNodeHandler); publisher = Mockito.mock(EventPublisher.class); nodeReportHandler = new NodeReportHandler(nodeManager); }

Target:
public void setup() throws IOException, AuthenticationException { OzoneConfiguration conf = new OzoneConfiguration(); storageDir = GenericTestUtils.getTempPath( TestDeadNodeHandler.class.getSimpleName() + UUID.randomUUID()); conf.set(HddsConfigKeys.OZONE_METADATA_DIRS, storageDir); conf.setInt(OZONE_DATANODE_MAX_PIPELINE_ENGAGEMENT, 0); eventQueue = new EventQueue(); scm = HddsTestUtils.getScm(conf); nodeManager = (SCMNodeManager) scm.getScmNodeManager(); SCMPipelineManager manager = (SCMPipelineManager)scm.getPipelineManager(); PipelineProvider mockRatisProvider = new MockRatisPipelineProvider(nodeManager, manager.getStateManager(), conf); manager.setPipelineProvider(HddsProtos.ReplicationType.RATIS, mockRatisProvider); containerManager = scm.getContainerManager(); deadNodeHandler = new DeadNodeHandler(nodeManager, Mockito.mock(PipelineManager.class), containerManager); eventQueue.addHandler(SCMEvents.DEAD_NODE, deadNodeHandler); publisher = Mockito.mock(EventPublisher.class); nodeReportHandler = new NodeReportHandler(nodeManager); }
Source:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Descriptor that = (Descriptor) o; return fullName.equals(that.fullName) && name.equals(that.name); }

Target:
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Descriptor that = (Descriptor) o; return fullName.equals(that.fullName); }
Source:
public AppPage clickAndConfirmWithoutWaitingForModalDisappearance(WebElement elementToClick) { click(elementToClick); waitForModalPresence(); WebElement okayButton = browser.driver.findElement(By.className("modal-btn-ok")); waitForElementToBeClickable(okayButton); click(okayButton); waitForPageToLoad(); return this; }

Target:
public void clickAndConfirmWithoutWaitingForModalDisappearance(WebElement elementToClick) { click(elementToClick); waitForModalPresence(); WebElement okayButton = browser.driver.findElement(By.className("modal-btn-ok")); waitForElementToBeClickable(okayButton); click(okayButton); }
Source:
public void testValidateCustomPropertiesWhenCustomPropertiesFeatureIsNotSupported() throws Exception { Network networkA = createNetworkWithName("networkA"); NetworkAttachment networkAttachment = createNetworkAttachment(networkA); Map<String, String> customProperties = new HashMap<>(); customProperties.put("a", "b"); networkAttachment.setProperties(customProperties); VDS host = new VDS(); host.setVdsGroupCompatibilityVersion(Version.v3_4); HostSetupNetworksParameters params = new HostSetupNetworksParameters(host.getId()); params.setNetworkAttachments(Collections.singletonList(networkAttachment)); HostSetupNetworksValidator validator = spy(new HostSetupNetworksValidatorBuilder() .setHost(host) .setParams(params) .setNetworkBusinessEntityMap(new BusinessEntityMap<>(Collections.singletonList(networkA))) .build()); doReturn(Collections.emptyList()).when(validator).translateErrorMessages(any(List.class)); assertThat(validator.validateCustomProperties(null, Collections.<String, String> emptyMap(), Collections.<String, String> emptyMap()), failsWith(VdcBllMessages.ACTION_TYPE_FAILED_NETWORK_CUSTOM_PROPERTIES_NOT_SUPPORTED)); }

Target:
public void testValidateCustomPropertiesWhenCustomPropertiesFeatureIsNotSupported() throws Exception { Network networkA = createNetworkWithName("networkA"); NetworkAttachment networkAttachment = createNetworkAttachment(networkA); Map<String, String> customProperties = new HashMap<>(); customProperties.put("a", "b"); networkAttachment.setProperties(customProperties); VDS host = new VDS(); host.setVdsGroupCompatibilityVersion(Version.v3_4); HostSetupNetworksParameters params = new HostSetupNetworksParameters(host.getId()); params.setNetworkAttachments(Collections.singletonList(networkAttachment)); HostSetupNetworksValidator validator = spy(new HostSetupNetworksValidatorBuilder() .setHost(host) .setParams(params) .setNetworkBusinessEntityMap(new BusinessEntityMap<>(Collections.singletonList(networkA))) .build()); doReturn(Collections.emptyList()).when(validator).translateErrorMessages(any(List.class)); assertThat(validator.validateCustomProperties(null, Collections.<String, String> emptyMap(), Collections.<String, String> emptyMap()), failsWith(EngineMessage.ACTION_TYPE_FAILED_NETWORK_CUSTOM_PROPERTIES_NOT_SUPPORTED)); }
Source:
public void testspaces() { StringBuffer buffer = new StringBuffer(); OracleDialect dialect = new OracleDialect(null); dialect.encodeColumnName("name with space",buffer); assertEquals("NAME WITH SPACE", buffer.toString()); }

Target:
public void testspaces() { StringBuffer buffer = new StringBuffer(); OracleDialect dialect = new OracleDialect(null); dialect.encodeColumnName("name with space",buffer); assertEquals("\"NAME WITH SPACE\"", buffer.toString()); }
Source:
public void putAll(Map<? extends K, ? extends V> m) { authzManager.checkPermission(CachePermission.WRITE); delegate.putAll(m); }

Target:
public void putAll(Map<? extends K, ? extends V> m) { authzManager.checkPermission(AuthorizationPermission.WRITE); delegate.putAll(m); }
Source:
public void onUpdate(U update) { synchronized (scheduleLock) { lastUpdate = update; if (schedule != null) { schedule.cancel(false); } schedule = getScheduledExecutorService().schedule(() -> getOriginal().onUpdate(lastUpdate), getPeriod(), getUnit()); } }

Target:
public void onUpdate(U update) { lastUpdate = update; ScheduledFuture<?> schedule = scheduleRef.get(); if (schedule != null) { schedule.cancel(INTERRUPT_RUNNING_UPDATE); } scheduleRef.compareAndSet(schedule, getScheduledExecutorService().schedule( () -> getDelegateUpdateHandler().onUpdate(lastUpdate), getPeriod(), getUnit())); }
Source:
private void registerMbean() { ObjectName objectName = null; MBeanServer mBeanServer = null; try { objectName = new ObjectName(Geocoding.class.getName() + ":service=geocoding"); mBeanServer = ManagementFactory.getPlatformMBeanServer(); } catch (MalformedObjectNameException e) { LOGGER.info("Unable to create Geocoding Configuration MBean.", e); } if (mBeanServer != null) { try { try { mBeanServer.registerMBean(this, objectName); LOGGER.debug( "Registered Geocoding Configuration MBean under object name: {}", objectName); } catch (InstanceAlreadyExistsException e) { mBeanServer.unregisterMBean(objectName); mBeanServer.registerMBean(this, objectName); LOGGER.debug("Re-registered Geocoding Configuration MBean"); } } catch (Exception e) { LOGGER.info("Could not register MBean [{}].", objectName.toString(), e); } } }

Target:
private void registerMbean() { try { ObjectName objectName = new ObjectName(Geocoding.class.getName() + ":service=geocoding"); MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); tryRegisterMBean(mBeanServer, objectName); } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | InstanceNotFoundException | NotCompliantMBeanException e) { LOGGER.info("Unable to create Geocoding Configuration MBean.", e); } }
Source:
public void sendEmail(String senderName, InternetAddress receiverAddress, String subjectTemplateName, String bodyTemplateName, Map<String, Object> templateParameters) { MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { String subjectText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email/" + subjectTemplateName + ".vm", "UTF-8", templateParameters); String bodyText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email/" + bodyTemplateName + ".vm", "UTF-8", templateParameters); MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setFrom(new InternetAddress(senderAddress, senderName)); message.setTo(receiverAddress); message.setSubject(subjectText); message.setText(bodyText, true); } }; this.mailSender.send(preparator); }

Target:
public void sendEmail(String senderName, InternetAddress receiverAddress, String subjectTemplateName, String bodyTemplateName, Map<String, Object> templateParameters) { LOGGER.info(MessageFormat.format("Sending e-mail to '{0}'. subjectTemplateName: {0}\r\n", receiverAddress, subjectTemplateName)); if (!yonaProperties.getEmail().isEnabled()) { LOGGER.info("E-mail sending is disabled. No message has been sent."); return; } MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(MimeMessage mimeMessage) throws Exception { String subjectText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email/" + subjectTemplateName + ".vm", "UTF-8", templateParameters); String bodyText = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "email/" + bodyTemplateName + ".vm", "UTF-8", templateParameters); MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setFrom(new InternetAddress(yonaProperties.getEmail().getSenderAddress(), senderName)); message.setTo(receiverAddress); message.setSubject(subjectText); message.setText(bodyText, true); } }; mailSender.send(preparator); LOGGER.info("E-mail sent succesfully."); }
Source:
private static void storeGroups(String groupFilePath, Multimap<String, String> groups) throws ManageUsersException { try { try (PrintWriter writer = new PrintWriter(new FileWriter(groupFilePath))) { for (String username : groups.keySet()) { for (String group : groups.get(username)) { writer.println(username + ":" + group); } } } } catch (IOException e) { exitWithErrorMessage("could not write group file : " + groupFilePath, null, e); } }

Target:
private static void storeGroups(String groupFilePath, Multimap<String, String> groups) throws ManageUsersException { try { try (PrintWriter writer = new PrintWriter(new FileWriter(groupFilePath))) { for (Map.Entry<String, String> userEntry : groups.entries()) { writer.println(userEntry.getKey() + ":" + userEntry.getValue()); } } } catch (IOException e) { exitWithErrorMessage("could not write group file : " + groupFilePath, null, e); } }
Source:
public EvaJobParameterBuilder inputStudyId(String inputStudyId) { super.addParameter(JobParametersNames.INPUT_STUDY_ID, new JobParameter(inputStudyId)); return this; }

Target:
public EvaJobParameterBuilder inputStudyId(String inputStudyId) { addParameter(JobParametersNames.INPUT_STUDY_ID, new JobParameter(inputStudyId)); return this; }
Source:
public HttpConnection execute() throws IOException { boolean retry = true; int n = numberOfRetries; while (retry && n-- > 0) { connection = connectionFactory.openConnection(url); connection.setRequestProperty("User-Agent", USER_AGENT); if (url.getUserInfo() != null) { requestInterceptors.add(0, new BasicAuthInterceptor(url.getUserInfo())); } connection.setDoInput(true); connection.setRequestMethod(requestMethod); if (contentType != null) { connection.setRequestProperty("Content-type", contentType); } HttpConnectionInterceptorContext currentContext = new HttpConnectionInterceptorContext(this); for (HttpConnectionRequestInterceptor requestInterceptor : requestInterceptors) { currentContext = requestInterceptor.interceptRequest(currentContext); } for (Map.Entry<String, String> property : requestProperties.entrySet()) { connection.setRequestProperty(property.getKey(), property.getValue()); } if (input != null) { connection.setDoOutput(true); if (inputLength != -1) { connection.setFixedLengthStreamingMode((int) this.inputLength); } else { connection.setChunkedStreamingMode(1024); } InputStream is = input.getInputStream(); OutputStream os = connection.getOutputStream(); try { try { IOUtils.copy(is, os); os.flush(); } finally { is.close(); } } finally { os.close(); } } for (HttpConnectionResponseInterceptor responseInterceptor : responseInterceptors) { currentContext = responseInterceptor.interceptResponse(currentContext); } retry = currentContext.replayRequest; if (n == 0) { logger.info("Maximum number of retries reached"); } } return this; }

Target:
public HttpConnection execute() throws IOException { boolean retry = true; int n = numberOfRetries; while (retry && n-- > 0) { connection = connectionFactory.openConnection(url); connection.setRequestProperty("User-Agent", USER_AGENT); if (url.getUserInfo() != null) { requestInterceptors.add(0, new BasicAuthInterceptor(url.getUserInfo())); } connection.setDoInput(true); connection.setRequestMethod(requestMethod); if (contentType != null) { connection.setRequestProperty("Content-type", contentType); } HttpConnectionInterceptorContext currentContext = new HttpConnectionInterceptorContext(this); for (HttpConnectionRequestInterceptor requestInterceptor : requestInterceptors) { currentContext = requestInterceptor.interceptRequest(currentContext); } for (Map.Entry<String, String> property : requestProperties.entrySet()) { connection.setRequestProperty(property.getKey(), property.getValue()); } if (input != null) { connection.setDoOutput(true); if (inputLength != -1) { connection.setFixedLengthStreamingMode((int) this.inputLength); } else { connection.setChunkedStreamingMode(1024); } InputStream is = input.getInputStream(); OutputStream os = connection.getOutputStream(); try { IOUtils.copy(is, os); os.flush(); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } for (HttpConnectionResponseInterceptor responseInterceptor : responseInterceptors) { currentContext = responseInterceptor.interceptResponse(currentContext); } retry = currentContext.replayRequest; if (n == 0) { logger.info("Maximum number of retries reached"); } } return this; }
Source:
public Map<Cell, byte[]> get(TableReference tableRef, Set<Cell> cells) { try { enterFunction.run(); return AtlasFutures.getUnchecked(delegate().getAsync(tableRef, cells)); } finally { exitFunction.run(); } }

Target:
public Map<Cell, byte[]> get(TableReference tableRef, Set<Cell> cells) { try (PathTypeTracker resource = tracker.enterAsyncPath()) { return AtlasFutures.getUnchecked(delegate().getAsync(tableRef, cells)); } }
Source:
static InetAddress[] restoreAddresses(final String address) throws DecoderException, UnknownHostException { final byte[] data = Hex.decodeHex(address.toCharArray()); if (data.length == 16) { for (int i = 0; i < 4; ++i) { ArrayUtils.reverse(data, i * 4, i * 4 + 4); } final InetAddress result = InetAddress.getByAddress(data); if (result instanceof Inet6Address) { if (InetAddresses.hasEmbeddedIPv4ClientAddress((Inet6Address) result)) { return new InetAddress[]{result, InetAddresses.getEmbeddedIPv4ClientAddress((Inet6Address) result)}; } } return new InetAddress[]{result}; } else { return new InetAddress[]{InetAddress.getByAddress(data)}; } }

Target:
private static InetAddress[] restoreAddresses(final String address) throws DecoderException, UnknownHostException { final byte[] data = Hex.decodeHex(address.toCharArray()); if (data.length == 16) { for (int i = 0; i < 4; ++i) { ArrayUtils.reverse(data, i * 4, i * 4 + 4); } final InetAddress result = InetAddress.getByAddress(data); if (result instanceof Inet6Address) { if (InetAddresses.hasEmbeddedIPv4ClientAddress((Inet6Address) result)) { return new InetAddress[]{result, InetAddresses.getEmbeddedIPv4ClientAddress((Inet6Address) result)}; } } return new InetAddress[]{result}; } else { ArrayUtils.reverse(data); return new InetAddress[]{InetAddress.getByAddress(data)}; } }
Source:
private CompletionStage<RestResponse> getSchemasNames(RestRequest request) { AdvancedCache<Object, Object> cache = invocationHelper.getRestCacheManager() .getCache(ProtobufMetadataManager.PROTOBUF_METADATA_CACHE_NAME, request); List<ProtoSchema> protoSchemas = cache.entrySet().stream() .filter(cacheEntry -> !((String)cacheEntry.getKey()).endsWith(ProtobufMetadataManager.ERRORS_KEY_SUFFIX)) .map(cacheEntry -> { String error = (String) cache .get(cacheEntry.getKey() + ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX); ProtoSchema protoSchema = new ProtoSchema(); protoSchema.name = cacheEntry.getKey().toString(); protoSchema.validation = error == null ? "success" : error; return protoSchema; }) .collect(Collectors.toList()); NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); try { responseBuilder .status(OK) .contentType(APPLICATION_JSON) .entity(invocationHelper.getMapper().writeValueAsBytes(protoSchemas)); } catch (JsonProcessingException e) { responseBuilder.status(HttpResponseStatus.INTERNAL_SERVER_ERROR); } return CompletableFuture.completedFuture(responseBuilder.build()); }

Target:
private CompletionStage<RestResponse> getSchemasNames(RestRequest request) { NettyRestResponse.Builder responseBuilder = new NettyRestResponse.Builder(); AdvancedCache<Object, Object> cache = invocationHelper.getRestCacheManager() .getCache(ProtobufMetadataManager.PROTOBUF_METADATA_CACHE_NAME, request); return CompletableFuture.supplyAsync(() -> Flowable.fromIterable(cache.keySet()) .filter(key -> !((String)key).endsWith(ProtobufMetadataManager.ERRORS_KEY_SUFFIX)) .map(key -> { String error = (String) cache .get(key + ProtobufMetadataManagerConstants.ERRORS_KEY_SUFFIX); ProtoSchema protoSchema = new ProtoSchema(); protoSchema.name = (String) key; if (error != null) { protoSchema.error = createErrorContent(protoSchema.name, error); } return protoSchema; }) .sorted(Comparator.comparing(s -> s.name)) .collect(Collectors.toList()) .map(protoSchemas -> { try { byte[] bytes = objectMapper.writeValueAsBytes(protoSchemas); responseBuilder.contentType(APPLICATION_JSON).entity(bytes); } catch (JsonProcessingException e) { throw new RestResponseException(e); } return (RestResponse) responseBuilder.build(); }) .toCompletionStage() , invocationHelper.getExecutor()) .thenCompose(Function.identity()); }
Source:
public LogFilePath(String prefix, String path) { assert path.startsWith(prefix): path + ".startsWith(" + prefix + ")"; mPrefix = prefix; int prefixLength = prefix.length(); if (!prefix.endsWith("/")) { prefixLength++; } String suffix = path.substring(prefixLength); String[] pathElements = suffix.split("/"); assert pathElements.length >= 3: Arrays.toString(pathElements) + ".length >= 3"; mTopic = pathElements[0]; mPartitions = subArray(pathElements, 1, pathElements.length - 2); String basename = pathElements[pathElements.length - 1]; int lastIndexOf = basename.indexOf('.'); if (lastIndexOf >= 0) { mExtension = basename.substring(lastIndexOf, basename.length()); basename = basename.substring(0, lastIndexOf); } else { mExtension = ""; } String[] basenameElements = basename.split("_"); assert basenameElements.length == 3: Integer.toString(basenameElements.length) + " == 3"; mGeneration = Integer.parseInt(basenameElements[0]); mKafkaPartitions = new int[]{Integer.parseInt(basenameElements[1])}; mOffsets = new long[]{Long.parseLong(basenameElements[2])}; }

Target:
public LogFilePath(String prefix, String path) { assert path.startsWith(prefix): path + ".startsWith(" + prefix + ")"; mPrefix = prefix; int prefixLength = prefix.length(); if (!prefix.endsWith("/")) { prefixLength++; } String suffix = path.substring(prefixLength); String[] pathElements = suffix.split("/"); assert pathElements.length >= 3: Arrays.toString(pathElements) + ".length >= 3"; mTopic = pathElements[0]; mPartitions = subArray(pathElements, 1, pathElements.length - 2); String basename = pathElements[pathElements.length - 1]; int indexOfSeparator = basename.indexOf('.'); if (indexOfSeparator >= 0) { mExtension = basename.substring(indexOfSeparator); basename = basename.substring(0, indexOfSeparator); } else { mExtension = ""; } String[] basenameElements = basename.split("_"); assert basenameElements.length == 3: basenameElements.length + " == 3"; mGeneration = Integer.parseInt(basenameElements[0]); mKafkaPartitions = new int[]{Integer.parseInt(basenameElements[1])}; mOffsets = new long[]{Long.parseLong(basenameElements[2])}; }
Source:
public Object consumePart(int byteCount) { ChannelOutboundBuffer buf = unsafe().outboundBuffer(); if (buf != null) { Object msg = buf.current(); if (msg instanceof ByteBuf) { ByteBuf byteBuf = (ByteBuf) msg; if (byteBuf.readableBytes() > byteCount) { buf.removeBytes(byteCount); return null; } else { ReferenceCountUtil.retain(msg); buf.removeBytes(byteCount); return msg; } } else { return null; } } return null; }

Target:
private Object consumePart(int byteCount) { ChannelOutboundBuffer buf = unsafe().outboundBuffer(); if (buf != null) { Object msg = buf.current(); if (msg != null) { ReferenceCountUtil.retain(msg); buf.removeBytes(byteCount); return msg; } } return null; }
Source:
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = (ConfigurableApplicationContext) applicationContext; }

Target:
public void setApplicationContext(ApplicationContext applicationContext) { this.context = (ConfigurableApplicationContext) applicationContext; }
Source:
public JSONObject jsonObject() { ContentType type = from(); JSONObject jsonObject; try { jsonObject = new JSONObject(mapper.writeValueAsString(type)); jsonObject.remove("permissionType"); jsonObject.remove("permissionId"); jsonObject.remove("versionable"); jsonObject.remove("multilingualable"); jsonObject.put("fields", new JsonFieldTransformer(type.fields()).jsonArray()); jsonObject.put(LAYOUT_PROPERTY_NAME, this.getLayoutAsJsonArray(type)); return jsonObject; } catch (JSONException | JsonProcessingException e) { throw new DotStateException(e); } }

Target:
public JSONObject jsonObject() { ContentType type = from(); JSONObject jsonObject; try { jsonObject = new JSONObject(mapper.writeValueAsString(type)); jsonObject.remove("permissionType"); jsonObject.remove("permissionId"); jsonObject.remove("versionable"); jsonObject.remove("multilingualable"); jsonObject.put("fields", new JsonFieldTransformer(type.fields()).jsonArray()); jsonObject.put(LAYOUT_PROPERTY_NAME, this.getLayoutAsJsonArray(type)); return jsonObject; } catch (JSONException | JsonProcessingException e) { Logger.error(JsonContentTypeTransformer.class, String.format("Error with the content type %s: %s", type.name(), e.getMessage())); throw new DotStateException(e); } }
Source:
public void clear() { long count = 0; boolean destroyDatabase = false; try { semaphore.acquire(); } catch (InterruptedException e) { throw new PersistenceException("Cannot acquire semaphore", e); } try { if (stopped) { throw new PersistenceException("RocksDB is stopped"); } Optional<RocksIterator> optionalIterator = getDBIterator(this.db); if (optionalIterator.isPresent() && configuration.clearThreshold() <= 0) { RocksIterator it = optionalIterator.get(); try { for(it.seekToFirst(); it.isValid(); it.next()) { db.remove(it.key()); count++; if (count > configuration.clearThreshold()) { destroyDatabase = true; break; } } } catch (RocksDBException e) { destroyDatabase = true; } finally { it.close(); } } else { destroyDatabase = true; } } finally { semaphore.release(); } if (destroyDatabase) { try { reinitAllDatabases(); } catch (Exception e) { throw new PersistenceException(e); } } }

Target:
public void clear() { long count = 0; boolean destroyDatabase = false; try { semaphore.acquire(); } catch (InterruptedException e) { throw new PersistenceException("Cannot acquire semaphore", e); } try { if (stopped) { throw new PersistenceException("RocksDB is stopped"); } Optional<RocksIterator> optionalIterator = wrapIterator(this.db); if (optionalIterator.isPresent() && configuration.clearThreshold() <= 0) { try (RocksIterator it = optionalIterator.get()) { for(it.seekToFirst(); it.isValid(); it.next()) { db.remove(it.key()); count++; if (count > configuration.clearThreshold()) { destroyDatabase = true; break; } } } catch (RocksDBException e) { destroyDatabase = true; } } else { destroyDatabase = true; } } finally { semaphore.release(); } if (destroyDatabase) { try { reinitAllDatabases(); } catch (Exception e) { throw new PersistenceException(e); } } }
Source:
public void testPublicAccess() throws InterruptedException, MalformedURLException, IOException { final String containerName = getScratchContainerName(); try { view.getBlobStore().createContainerInLocation(null, containerName, publicRead()); assertConsistencyAwareContainerExists(containerName); defaultLocation = Iterables.find(view.getBlobStore().list(), new Predicate<StorageMetadata>() { @Override public boolean apply(@Nullable StorageMetadata input) { return input.getName().equals(containerName); } }).getLocation(); view.getBlobStore().putBlob(containerName, view.getBlobStore().blobBuilder("hello").payload(TEST_STRING).build()); assertConsistencyAwareContainerSize(containerName, 1); BlobMetadata metadata = view.getBlobStore().blobMetadata(containerName, "hello"); assert metadata.getPublicUri() != null : metadata; SocketOpen socketOpen = context.utils().injector().getInstance(SocketOpen.class); Predicate<HostAndPort> socketTester = retry(socketOpen, 1200, 10, SECONDS); assert socketTester.apply(HostAndPort.fromHost(metadata.getPublicUri().getHost()).withDefaultPort(80)) : metadata.getPublicUri(); assertEquals(Strings2.toStringAndClose(view.utils().http().get(metadata.getPublicUri())), TEST_STRING); } finally { recycleContainerAndAddToPool(containerName); } }

Target:
public void testPublicAccess() throws InterruptedException, MalformedURLException, IOException { final String containerName = getScratchContainerName(); try { view.getBlobStore().createContainerInLocation(null, containerName, publicRead()); assertConsistencyAwareContainerExists(containerName); defaultLocation = Iterables.find(view.getBlobStore().list(), new Predicate<StorageMetadata>() { @Override public boolean apply(@Nullable StorageMetadata input) { return input.getName().equals(containerName); } }).getLocation(); view.getBlobStore().putBlob(containerName, view.getBlobStore().blobBuilder("hello").payload(TEST_STRING).build()); assertConsistencyAwareContainerSize(containerName, 1); BlobMetadata metadata = view.getBlobStore().blobMetadata(containerName, "hello"); assertTrue(metadata.getPublicUri() != null, metadata.toString()); SocketOpen socketOpen = context.utils().injector().getInstance(SocketOpen.class); Predicate<HostAndPort> socketTester = retry(socketOpen, 1200, 10, SECONDS); assertTrue(socketTester.apply(HostAndPort.fromHost(metadata.getPublicUri().getHost()).withDefaultPort(80)), metadata.getPublicUri().toString()); assertEquals(Strings2.toStringAndClose(view.utils().http().get(metadata.getPublicUri())), TEST_STRING); } finally { recycleContainerAndAddToPool(containerName); } }
Source:
public synchronized void cancelPendingRequests(String registrationId) { ArrayList<Request> requests = pendingRequests.get(registrationId); if (requests != null) { for (Request coapRequest : requests) { coapRequest.cancel(); removePendingRequest(registrationId, coapRequest); } } }

Target:
public void cancelPendingRequests(String registrationId) { SortedMap<String, Request> requests = pendingRequests.subMap(getFloorKey(registrationId), getCeilingKey(registrationId)); for (Request coapRequest : requests.values()) { coapRequest.cancel(); } requests.clear(); }
Source:
public void setUp() { executor = newScheduledThreadPool(10, daemonThreadsNamed("test-merge-operator-%s")); serdeFactory = new TestingPagesSerdeFactory(); taskBuffers = CacheBuilder.newBuilder().build(CacheLoader.from(TestingTaskBuffer::new)); httpClient = new TestingHttpClient(new TestingExchangeHttpClientHandler(taskBuffers), executor); exchangeClientFactory = new ExchangeClientFactory(new ExchangeClientConfig(), httpClient, executor); }

Target:
public void setUp() { executor = newSingleThreadScheduledExecutor(daemonThreadsNamed("test-merge-operator-%s")); serdeFactory = new TestingPagesSerdeFactory(); taskBuffers = CacheBuilder.newBuilder().build(CacheLoader.from(TestingTaskBuffer::new)); httpClient = new TestingHttpClient(new TestingExchangeHttpClientHandler(taskBuffers), executor); exchangeClientFactory = new ExchangeClientFactory(new ExchangeClientConfig(), httpClient, executor); orderingCompiler = new OrderingCompiler(); }
Source:
public ProgrammaticTomcat() { this.randomPort = new Random() .ints(6000, 9000) .findFirst() .orElse(8080); }

Target:
public ProgrammaticTomcat() { this.randomPort = new Random() .ints(6000, 9000) .filter(ProgrammaticTomcat::isFree) .findFirst() .orElse(8080); }
Source:
public void validate_shouldFailValidationIfDateActivatedAfterDateStopped() throws Exception { RadiologyOrder radiologyOrder = new RadiologyOrder(); radiologyOrder.setConcept(Context.getConceptService() .getConcept(88)); radiologyOrder.setPatient(Context.getPatientService() .getPatient(2)); radiologyOrder.setOrderer(Context.getProviderService() .getProvider(1)); Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - 1); radiologyOrder.setDateActivated(new Date()); OrderUtilTest.setDateStopped(radiologyOrder, cal.getTime()); Errors errors = new BindException(radiologyOrder, "radiologyOrder"); new RadiologyOrderValidator().validate(radiologyOrder, errors); assertTrue(errors.hasFieldErrors("dateActivated")); assertTrue(errors.hasFieldErrors("dateStopped")); }

Target:
public void validate_shouldFailValidationIfDateActivatedAfterDateStopped() throws Exception { RadiologyOrder radiologyOrder = getValidRadiologyOrder(); Calendar cal = Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - 1); radiologyOrder.setDateActivated(new Date()); OrderUtilTest.setDateStopped(radiologyOrder, cal.getTime()); Errors errors = new BindException(radiologyOrder, "radiologyOrder"); new RadiologyOrderValidator().validate(radiologyOrder, errors); assertTrue(errors.hasFieldErrors("dateActivated")); assertTrue(errors.hasFieldErrors("dateStopped")); }
Source:
private boolean isGlobalFailure(ITestResult result) { ITestNGMethod m = result.getMethod(); return m.isBeforeTestConfiguration() || m.isBeforeSuiteConfiguration(); }

Target:
private static boolean isGlobalFailure(ITestResult result) { ITestNGMethod m = result.getMethod(); return m.isBeforeTestConfiguration() || m.isBeforeSuiteConfiguration(); }
Source:
public ArrayList<String> toggleLabel(String name) { removePossibleLabel(); ArrayList<String> removedLabels = processAndUpdateTopLabels(name); restoreBottomLabels(); populatePanes(); return removedLabels; }

Target:
public ArrayList<String> toggleLabel(String name) { removePossibleLabel(); ArrayList<String> removedLabels = resolveConflictsAndUpdateLabels(name); resetMatchingLabels(); populatePanes(); return removedLabels; }
Source:
private InboundTransferTask addTransfer(Address source, Set<Integer> segmentsFromSource) { synchronized (transferMapsLock) { log.tracef("Adding transfer from %s for segments %s", source, segmentsFromSource); segmentsFromSource.removeAll(transfersBySegment.keySet()); if (segmentsFromSource.isEmpty()) { log.tracef("All segments are already in progress, skipping"); return null; } else { final InboundTransferTask inboundTransfer = new InboundTransferTask(segmentsFromSource, source, cacheTopology.getTopologyId(), this, rpcManager, commandsFactory, timeout, cacheName); for (int segmentId : segmentsFromSource) { transfersBySegment.put(segmentId, inboundTransfer); } List<InboundTransferTask> inboundTransfers = transfersBySource.get(inboundTransfer.getSource()); if (inboundTransfers == null) { inboundTransfers = new ArrayList<InboundTransferTask>(); transfersBySource.put(inboundTransfer.getSource(), inboundTransfers); } inboundTransfers.add(inboundTransfer); stateRequestCompletionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { inboundTransfer.requestSegments(); log.debugf("Waiting for inbound transfer to finish: %s", inboundTransfer); stateRequestCompletionService.continueTaskInBackground(); return null; } }); return inboundTransfer; } } }

Target:
private InboundTransferTask addTransfer(Address source, Set<Integer> segmentsFromSource) { synchronized (transferMapsLock) { if (trace) log.tracef("Adding transfer from %s for segments %s", source, segmentsFromSource); segmentsFromSource.removeAll(transfersBySegment.keySet()); if (segmentsFromSource.isEmpty()) { if (trace) log.tracef("All segments are already in progress, skipping"); return null; } else { final InboundTransferTask inboundTransfer = new InboundTransferTask(segmentsFromSource, source, cacheTopology.getTopologyId(), this, rpcManager, commandsFactory, timeout, cacheName); for (int segmentId : segmentsFromSource) { transfersBySegment.put(segmentId, inboundTransfer); } List<InboundTransferTask> inboundTransfers = transfersBySource.get(inboundTransfer.getSource()); if (inboundTransfers == null) { inboundTransfers = new ArrayList<InboundTransferTask>(); transfersBySource.put(inboundTransfer.getSource(), inboundTransfers); } inboundTransfers.add(inboundTransfer); stateRequestCompletionService.submit(new Callable<Void>() { @Override public Void call() throws Exception { inboundTransfer.requestSegments(); if (trace) log.tracef("Waiting for inbound transfer to finish: %s", inboundTransfer); stateRequestCompletionService.continueTaskInBackground(); return null; } }); return inboundTransfer; } } }
Source:
private String getShareSubject() { if (getArguments().getBoolean(ARG_FEED_FEATURED_IMAGE)) { return ShareUtil.getFeaturedImageShareSubject(getContext(), new UtcDate(age).baseCalendar()); } else if (pageTitle != null) { return pageTitle.getDisplayText(); } return null; }

Target:
private String getShareSubject() { return getArguments().getBoolean(ARG_FEED_FEATURED_IMAGE) ? ShareUtil.getFeaturedImageShareSubject(getContext(), age) : null; }