auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private List<Target<Object>> createTargets(ControllerMethod method) { Method javaMethod = method.getMethod(); List<Target<Object>> targets = new ArrayList<>(); <START> List<br.com.caelum.vraptor.http.Parameter> parameterNames = nameProvider.parametersFor(javaMethod); <END> for (br.com.caelum.vraptor.http.Parameter p : parameterNames) { Type type = p.getParameterizedType(); if (type instanceof TypeVariable) { type = extractType(method); } targets.add(new Target<>(type, p.getName())); } return targets; }</code><technical_language>Inline this, please. FQNs ugly</technical_language>

Target:
private List<Target<Object>> createTargets(ControllerMethod method) { Method javaMethod = method.getMethod(); List<Target<Object>> targets = new ArrayList<>(); for (br.com.caelum.vraptor.http.Parameter p : nameProvider.parametersFor(javaMethod)) { Type type = p.getParameterizedType(); if (type instanceof TypeVariable) { type = extractType(method); } targets.add(new Target<>(type, p.getName())); } return targets; }
Source:
<code>private void createBooleanAccessor() { accessors.put(Boolean.class, new Accessor<Boolean>() { @Override public Boolean get(String key, Boolean defaultValue) { <START> return preferences.getBoolean(key, (defaultValue == null) ? false : defaultValue); <END> } @Override public void put(String key, Boolean value) { editor.putBoolean(key, value).apply(); } }); }</code><technical_language>In this case, defining default behavior for user in case of passing null. if a user wants true false, forcing of these. rule applies of changes below</technical_language>

Target:
private void createBooleanAccessor() { accessors.put(Boolean.class, new Accessor<Boolean>() { @Override public Boolean get(String key) { return preferences.getBoolean(key, false); } @Override public void put(String key, Boolean value) { editor.putBoolean(key, value).apply(); } }); }
Source:
<code>public static List<RelCollation> calc(RelMetadataQuery mq, RelNode input, RexProgram program) { final List<RexNode> projects = program .getProjectList() .stream() .map((p) -> program.expandLocalRef(p)) .collect(Collectors.toList()); <START> return enumrableCalc(mq, input, projects); <END> }</code><technical_language>easier leave project method unchanged, return: return project(mq, input, projects);</technical_language>

Target:
public static List<RelCollation> calc(RelMetadataQuery mq, RelNode input, RexProgram program) { final List<RexNode> projects = program .getProjectList() .stream() .map((p) -> program.expandLocalRef(p)) .collect(Collectors.toList()); return project(mq, input, projects); }
Source:
<code>private void updateGameMode( CommandSender sender, Player who, GameMode gameMode, ResourceBundle bundle) { String gameModeName = GameModeUtils.prettyPrint(gameMode, bundle.getLocale()); who.setGameMode(gameMode); if (sender.equals(who)) { new LocalizedStringImpl("gamemode.done.self", bundle).send(sender, gameModeName); } else { <START> new LocalizedStringImpl("gamemode.done", bundle) <END> .send(sender, who.getDisplayName(), gameModeName); } }</code><technical_language>This changes behavior longer notifying player gamemode set</technical_language>

Target:
private void updateGameMode( CommandSender sender, Player who, GameMode gameMode, ResourceBundle bundle) { String gameModeName = GameModeUtils.prettyPrint(gameMode, bundle.getLocale()); who.setGameMode(gameMode); if (!sender.equals(who)) { new LocalizedStringImpl("gamemode.done", bundle) .send(sender, who.getDisplayName(), gameModeName); } new LocalizedStringImpl("gamemode.done.to-you", bundle).send(who, gameModeName); }
Source:
<code>BackgroundLocationMessage activityDisplayed() { switch (currentState) { case PENDING_PRECONDITION_CHECKS: BackgroundLocationMessage userMessage = null; if (!helper.isBackgroundLocationPreferenceEnabled()) { helper.logAuditEvent(AuditEvent.AuditEventType.LOCATION_TRACKING_DISABLED); userMessage = BackgroundLocationMessage.LOCATION_PREF_DISABLED; } if (!helper.arePlayServicesAvailable()) { helper.logAuditEvent(AuditEvent.AuditEventType.GOOGLE_PLAY_SERVICES_NOT_AVAILABLE); userMessage = BackgroundLocationMessage.PLAY_SERVICES_UNAVAILABLE; } if (userMessage == null) { helper.logAuditEvent(AuditEvent.AuditEventType.LOCATION_TRACKING_ENABLED); currentState = BackgroundLocationState.PENDING_PERMISSION_CHECK; } else { currentState = BackgroundLocationState.STOPPED; } return userMessage; <START> case RECEIVING_LOCATIONS: <END> if (!helper.isAndroidLocationPermissionGranted()) { helper.logAuditEvent(AuditEvent.AuditEventType.LOCATION_PERMISSIONS_NOT_GRANTED); stopLocationRequests(); } else { startLocationRequests(); } break; case STOPPED: if (helper.isAndroidLocationPermissionGranted()) { helper.logAuditEvent(AuditEvent.AuditEventType.LOCATION_PERMISSIONS_GRANTED); } startLocationRequests(); break; } return null; }</code><technical_language>Running BackgroundLocationManagerTest coverage this case hit of tests</technical_language>

Target:
public BackgroundLocationMessage activityDisplayed() { switch (currentState) { case NO_BACKGROUND_LOCATION_NEEDED: if (helper.isCurrentFormSet() && helper.currentFormAuditsLocation()) { startLocationRequests(); if (currentState != BackgroundLocationState.RECEIVING_LOCATIONS) { currentState = BackgroundLocationState.STOPPED; } } break; case PENDING_PRECONDITION_CHECKS: BackgroundLocationMessage userMessage = null; if (!helper.isBackgroundLocationPreferenceEnabled()) { helper.logAuditEvent(AuditEvent.AuditEventType.LOCATION_TRACKING_DISABLED); userMessage = BackgroundLocationMessage.LOCATION_PREF_DISABLED; } if (!helper.arePlayServicesAvailable()) { helper.logAuditEvent(AuditEvent.AuditEventType.GOOGLE_PLAY_SERVICES_NOT_AVAILABLE); userMessage = BackgroundLocationMessage.PLAY_SERVICES_UNAVAILABLE; } if (userMessage == null) { helper.logAuditEvent(AuditEvent.AuditEventType.LOCATION_TRACKING_ENABLED); currentState = BackgroundLocationState.PENDING_PERMISSION_CHECK; } else { currentState = BackgroundLocationState.STOPPED; } return userMessage; case STOPPED: startLocationRequests(); break; } return null; }
Source:
<code>private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("European Variation Archive REST Web Services API") <START> .contact(new Contact("the European Variation Archive team", "www.ebi.ac.uk/eva", "eva-helpdesk@ebi.ac.uk")) <END> .license("Apache License Version 2.0") .licenseUrl("<LINK_0>") .version("1.0") .build(); }</code><technical_language>recommended existing DGVa branding, details converted into: * Database of Genomic Variants Archive REST Web Services API * Database of Genomic Variants Archive team * www.ebi.ac.uk/dgva * dgva-helpdesk@ebi.ac.uk</technical_language>

Target:
private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Database of Genomic Variants Archive REST Web Services API") .contact(new Contact("the Database of Genomic Variants Archive team", "www.ebi.ac.uk/dgva", "dgva-helpdesk@ebi.ac.uk")) .license("Apache License Version 2.0") .licenseUrl("<LINK_0>") .version("1.0") .build(); }
Source:
<code>private VDSFenceReturnValue fence(FenceAgent fenceAgent, int retries) { FenceExecutor fenceExecutor = createFenceExecutor(); VDSFenceReturnValue fenceExecutionResult = fenceExecutor.fence(getAction(), fenceAgent); if (wasSkippedDueToStatus(fenceExecutionResult)) { log.info("Attemp to VDS using fence agent{} skipped: Host is already at the requested state.", getAction().name().toLowerCase(), fenceAgent.getId()); } else if (wasSkippedDueToPolicy(fenceExecutionResult)) { return fenceExecutionResult; <START> } else { <END> if (fenceExecutionResult.getSucceeded()) { boolean requiredStatusAchieved = waitForStatus(); int i = 0; while (!requiredStatusAchieved && i < retries) { fenceExecutionResult = fenceExecutor.fence(getAction(), fenceAgent); requiredStatusAchieved = waitForStatus(); i++; } if (requiredStatusAchieved) { handleSpecificCommandActions(); } else { auditFailure(); } fenceExecutionResult.setSucceeded(requiredStatusAchieved); } else { logAgentFailure(fenceExecutionResult); } } return fenceExecutionResult; }</code><technical_language>Agreed, this a bug :)</technical_language>

Target:
private VDSFenceReturnValue fence(FenceAgent fenceAgent, int retries) { FenceExecutor fenceExecutor = createFenceExecutor(); VDSFenceReturnValue fenceExecutionResult = fenceExecutor.fence(getAction(), fenceAgent); if (wasSkippedDueToStatus(fenceExecutionResult)) { log.info("Attemp to host using fence agent '{}' skipped, host is already at the requested state.", getAction().name().toLowerCase(), fenceAgent.getId()); } else if (wasSkippedDueToPolicy(fenceExecutionResult)) { return fenceExecutionResult; } else { if (fenceExecutionResult.getSucceeded()) { boolean requiredStatusAchieved = waitForStatus(); int i = 0; while (!requiredStatusAchieved && i < retries) { fenceExecutionResult = fenceExecutor.fence(getAction(), fenceAgent); requiredStatusAchieved = waitForStatus(); i++; } if (requiredStatusAchieved) { handleSpecificCommandActions(); } else { auditFailure(); } fenceExecutionResult.setSucceeded(requiredStatusAchieved); } else { logAgentFailure(fenceExecutionResult); } } return fenceExecutionResult; }
Source:
<code>public void shouldHandleAnAuthorisedCancelledNotification_whenChargeIsInUserCancelSubmittedState() throws Exception { String transactionId = "transaction-id"; String chargeId = createNewChargeWith(USER_CANCEL_SUBMITTED, transactionId); <START> String epdqAuthorisedCancelledNotificationCode = "6"; <END> String response = notifyConnector( transactionId, "1", epdqAuthorisedCancelledNotificationCode, getCredentials().get(CREDENTIALS_SHA_OUT_PASSPHRASE) ) .statusCode(200) .extract().body() .asString(); assertThat(response, is(RESPONSE_EXPECTED_BY_EPDQ)); assertFrontendChargeStatusIs(chargeId, USER_CANCELLED.getValue()); }</code><technical_language>clearer if "6" replaced EpdqStatusMapper.EPDQ_AUTHORISED_CANCELLED</technical_language>

Target:
public void shouldHandleAnAuthorisedCancelledNotification_whenChargeIsInUserCancelSubmittedState() throws Exception { String transactionId = "transaction-id"; String chargeId = createNewChargeWith(USER_CANCEL_SUBMITTED, transactionId); String epdqAuthorisedCancelledNotificationCode = EPDQ_AUTHORISED_CANCELLED.getCode(); String response = notifyConnector( transactionId, "1", epdqAuthorisedCancelledNotificationCode, getCredentials().get(CREDENTIALS_SHA_OUT_PASSPHRASE) ) .statusCode(200) .extract().body() .asString(); assertThat(response, is(RESPONSE_EXPECTED_BY_EPDQ)); assertFrontendChargeStatusIs(chargeId, USER_CANCELLED.getValue()); }
Source:
<code>public boolean tick() { profiler.startSection("providerTick"); long i = System.currentTimeMillis(); int randomTickSpeed = this.world.getGameRules().getInt("randomTickSpeed"); Random rand = this.world.rand; PlayerCubeMap playerCubeMap = ((PlayerCubeMap)this.world.getPlayerChunkMap()); Iterator<CubeWatcher> watchersIterator = playerCubeMap.getCubeWatcherIterator(); while (watchersIterator.hasNext()) { Cube cube = watchersIterator.next().getCube(); if (cube == null) continue; cube.tickCubeServer(() -> System.currentTimeMillis() - i > 40, rand); if (cube.isEmpty() || !doRandomBlockTicksHere) continue; int randomTickCounter = randomTickSpeed; while (randomTickCounter-- > 0) cube.randomTick(this.world, rand); <START> } <END> profiler.endSection(); return false; }</code><technical_language>Formatting</technical_language>

Target:
public boolean tick() { profiler.startSection("providerTick"); long i = System.currentTimeMillis(); int randomTickSpeed = this.world.getGameRules().getInt("randomTickSpeed"); Random rand = this.world.rand; PlayerCubeMap playerCubeMap = ((PlayerCubeMap) this.world.getPlayerChunkMap()); Iterator<Cube> watchersIterator = playerCubeMap.getCubeIterator(); while (watchersIterator.hasNext()) { Cube cube = watchersIterator.next(); cube.tickCubeServer(() -> System.currentTimeMillis() - i > 40, rand); if (!doRandomBlockTicksHere) continue; int randomTickCounter = randomTickSpeed; while (randomTickCounter-- > 0) cube.randomTick(this.world, rand); } profiler.endSection(); return false; }
Source:
<code>protected String doInBackground(Object[] params) { String result = null; if (params.length == 3) { Uri uri = (Uri) params[0]; String filePath = (String) params[1]; mIndex = ((Integer) params[2]).intValue(); String fullTempPath = FileStorageUtils.getTemporalPath(mAccountName) + filePath; InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = mContentResolver.openInputStream(uri); File cacheFile = new File(fullTempPath); File tempDir = cacheFile.getParentFile(); if (!tempDir.exists()) { tempDir.mkdirs(); } cacheFile.createNewFile(); outputStream = new FileOutputStream(fullTempPath); byte[] buffer = new byte[4096]; int count = 0; while ((count = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, count); } outputStream.close(); inputStream.close(); result = fullTempPath; } catch (Exception e) { Log_OC.e(TAG, "Exception ", e); if (inputStream != null) { try { inputStream.close(); } catch (Exception e1) { Log_OC.e(TAG, "Input Stream Exception ", e1); } } if (outputStream != null) { try { outputStream.close(); } catch (Exception e1) { Log_OC.e(TAG, "Output Stream Exception ", e1); } } if (fullTempPath != null) { File f = new File(fullTempPath); f.delete(); } result = null; } } else { <START> Log_OC.e(TAG, "Error in parameters number"); <END> } return result; }</code><technical_language>This more "assertive"; throw IllegalArgumentException break app. This a programming error, error condition in runtime</technical_language>

Target:
protected String doInBackground(Object[] params) { String result = null; if (params != null && params.length == 5) { Uri uri = (Uri) params[0]; String filePath = (String) params[1]; mIndex = ((Integer) params[2]).intValue(); String accountName = (String) params[3]; ContentResolver contentResolver = (ContentResolver) params[4]; String fullTempPath = FileStorageUtils.getTemporalPath(accountName) + filePath; InputStream inputStream = null; FileOutputStream outputStream = null; try { inputStream = contentResolver.openInputStream(uri); File cacheFile = new File(fullTempPath); File tempDir = cacheFile.getParentFile(); if (!tempDir.exists()) { tempDir.mkdirs(); } cacheFile.createNewFile(); outputStream = new FileOutputStream(fullTempPath); byte[] buffer = new byte[4096]; int count = 0; while ((count = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, count); } outputStream.close(); inputStream.close(); result = fullTempPath; } catch (Exception e) { Log_OC.e(TAG, "Exception ", e); if (inputStream != null) { try { inputStream.close(); } catch (Exception e1) { Log_OC.e(TAG, "Input Stream Exception ", e1); } } if (outputStream != null) { try { outputStream.close(); } catch (Exception e1) { Log_OC.e(TAG, "Output Stream Exception ", e1); } } if (fullTempPath != null) { File f = new File(fullTempPath); f.delete(); } result = null; } } else { throw new IllegalArgumentException("Error in parameters number"); } return result; }
Source:
<code>public TranslationFormat getFormat() { <START> String formatStr = manifest.getString("format"); <END> TranslationFormat format = TranslationFormat.get(formatStr); if(null == format) { return TranslationFormat.USX; } return format; }</code><technical_language>this change move loading of this information constructor do file io time this is called</technical_language>

Target:
public TranslationFormat getFormat() { return mTranslationFormat; }
Source:
<code>private void checkValidXML(String content) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); InputSource input = new InputSource(new StringReader(content.replaceAll("\n", ""))); Document doc = docBuilder.parse(input); doc.getDocumentElement().normalize(); NodeList orders = doc.getElementsByTagName("Order"); if (orders.getLength() == 0) { results.error("Missing 'Order' tag in the contents"); } else { for (int i = 0; i < orders.getLength(); i++) { Node order = orders.item(i); if (!order.hasAttributes()) { results.error("RelationOrder has no attributes"); } } } <START> } catch (Exception ex) { <END> results.error(ex.toString()); } }</code><technical_language>Lib.exceptionToString(ex). ex.toString work, I</technical_language>

Target:
private void checkValidXML(String content) { try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbFactory.newDocumentBuilder(); InputSource input = new InputSource(new StringReader(content.replaceAll("\n", ""))); Document doc = docBuilder.parse(input); doc.getDocumentElement().normalize(); NodeList orders = doc.getElementsByTagName("Order"); if (orders.getLength() == 0) { results.errorf("Missing 'Order' tag in the contents"); } else { for (int i = 0; i < orders.getLength(); i++) { Node order = orders.item(i); if (!order.hasAttributes()) { results.errorf("RelationOrder has no attributes"); } } } } catch (Exception ex) { results.errorf(Lib.exceptionToString(ex)); } }
Source:
<code>public String generateDisplayNameForClass(Class<?> testClass) { <START> return replaceUnderscores(testClass.getSimpleName()); <END> }</code><technical_language>this change ReplaceUnderscores? (sorry if explained it, I remember... )</technical_language>

Target:
public String generateDisplayNameForClass(Class<?> testClass) { return replaceUnderscores(super.generateDisplayNameForClass(testClass)); }
Source:
<code>default long readLong() throws IOException { <START> byte[] buf = new byte[8]; <END> int read = read(buf, 0, 8); if (read < 0) { throw new EOFException(); } return Bytes.toLong(buf, isLittleEndian()); }</code><technical_language>Need a reusable buffer</technical_language>

Target:
default long readLong() throws IOException { final byte[] buf = conversionBuffer(); final int read = read(buf, 0, 8); if (read < 8) { throw new EOFException(); } return Bytes.toLong(buf, isLittleEndian()); }
Source:
<code>public Iterable<Language> languages() { final RtJson rtJson = new RtJson( this.request.uri() .path("/languages") .back() ); <START> JsonObject json; <END> try { json = rtJson.fetch(); } catch (final IOException ex) { throw new IllegalStateException(ex); } final int size = json.size(); final List<Language> languages = new ArrayList<Language>(size); for (final Map.Entry<String, JsonValue> value : json.entrySet()) { final String name = value.getKey(); final JsonNumber bytesJsonNumber = json.getJsonNumber(name); final long bytes = bytesJsonNumber.longValue(); final Language language = new RtLanguage(name, bytes); languages.add(language); } return languages; }</code><technical_language>json final</technical_language>

Target:
public Iterable<Language> languages() { final RtJson rtJson = new RtJson( this.request.uri() .path("/languages") .back() ); final JsonObject json; try { json = rtJson.fetch(); } catch (final IOException ex) { throw new IllegalStateException(ex); } final List<Language> languages = new ArrayList<Language>(json.size()); for (final Map.Entry<String, JsonValue> value : json.entrySet()) { final String name = value.getKey(); languages.add( new RtLanguage( name, json.getJsonNumber(name).longValue() ) ); } return languages; }
Source:
<code>public List<TargetSummaryBean> list() throws DtgovUiException { SrampAtomApiClient client = _srampClientAccessor.getClient(); SrampClientQuery query = client.buildQuery("/s-ramp/ext/" + TargetConstants.TARGET_EXTENDED_TYPE); <START> SrampClientQuery scq = query.startIndex(0).orderBy("name"); END> scq.propertyName(TargetConstants.TARGET_TYPE); scq = scq.ascending(); try { QueryResultSet resultSet = scq.query(); List<TargetSummaryBean> summary = TargetFactory.asList(resultSet); return summary; } catch (SrampClientException e) { throw new DtgovUiException(e); } catch (SrampAtomException e) { throw new DtgovUiException(e); } }</code><technical_language>create another variable named 'scq'. methods calling change internal state of SrampClientQuery return "this" (aka a fluent API). In other words, this line of code is true: query == scq</technical_language>

Target:
public List<TargetSummaryBean> list() throws DtgovUiException { SrampAtomApiClient client = _srampClientAccessor.getClient(); SrampClientQuery query = client.buildQuery("/s-ramp/ext/" + TargetConstants.TARGET_EXTENDED_TYPE); query = query.startIndex(0).orderBy("name"); query.propertyName(TargetConstants.TARGET_TYPE); query = query.ascending(); try { QueryResultSet resultSet = query.query(); List<TargetSummaryBean> summary = TargetFactory.asList(resultSet); return summary; } catch (SrampClientException e) { throw new DtgovUiException(e); } catch (SrampAtomException e) { throw new DtgovUiException(e); } }
Source:
<code>public void filterCheckerWorkflows() { Workflow workflow = new Workflow(); workflow.setIsChecker(true); Tool tool = new Tool(); <START> List<Entry> entries = manager.filterCheckerWorkflows(Arrays.asList(workflow, tool)); <END> Assert.assertEquals("There should've been 1 entry without checker workflow", 1, entries.size()); entries.forEach(entry -> Assert.assertFalse("There should be no workflow", entry instanceof Workflow)); }</code><technical_language>logic straightforward doubt works, nice test a non-checker Workflow in list well</technical_language>

Target:
public void filterCheckerWorkflows() { Workflow checkerWorkflow = new Workflow(); checkerWorkflow.setIsChecker(true); Workflow workflow = new Workflow(); workflow.setIsChecker(false); Tool tool = new Tool(); List<Entry> entries = manager.filterCheckerWorkflows(Arrays.asList(workflow, tool, checkerWorkflow)); Assert.assertEquals("There should've been 2 entries without the checker workflow", 2, entries.size()); entries.forEach(entry -> Assert.assertFalse("There should be no checker workflows", entry instanceof Workflow && ((Workflow)entry).isIsChecker())); }
Source:
<code>public SubmoduleWalk loadModulesConfig() throws IOException, ConfigInvalidException { <START> if (useWorkingTree) { <END> File modulesFile = new File(repository.getWorkTree(), Constants.DOT_GIT_MODULES); FileBasedConfig config = new FileBasedConfig(modulesFile, repository.getFS()); config.load(); modulesConfig = config; } else if (rootTree != null) { TreeWalk configWalk = new TreeWalk(repository); try { configWalk.addTree(rootTree); int idx; for (idx = 0; !rootTree.first(); idx++) { rootTree.back(1); } try { configWalk.setRecursive(false); PathFilter filter = PathFilter.create(Constants.DOT_GIT_MODULES); configWalk.setFilter(filter); while (configWalk.next()) { if (filter.isDone(configWalk)) { modulesConfig = new BlobBasedConfig(null, repository, configWalk.getObjectId(0)); return this; } } if (!useWorkingTree) { modulesConfig = new Config(); return this; } } finally { if (idx > 0) rootTree.next(idx); } } finally { configWalk.release(); } } return this; }</code><technical_language>simplifying this a single if/else rootTree if non-null falls working tree config if rootTree is null? useWorkingTree field removed</technical_language>

Target:
public SubmoduleWalk loadModulesConfig() throws IOException, ConfigInvalidException { if (rootTree == null) { File modulesFile = new File(repository.getWorkTree(), Constants.DOT_GIT_MODULES); FileBasedConfig config = new FileBasedConfig(modulesFile, repository.getFS()); config.load(); modulesConfig = config; } else { TreeWalk configWalk = new TreeWalk(repository); try { configWalk.addTree(rootTree); int idx; for (idx = 0; !rootTree.first(); idx++) { rootTree.back(1); } try { configWalk.setRecursive(false); PathFilter filter = PathFilter.create(Constants.DOT_GIT_MODULES); configWalk.setFilter(filter); while (configWalk.next()) { if (filter.isDone(configWalk)) { modulesConfig = new BlobBasedConfig(null, repository, configWalk.getObjectId(0)); return this; } } modulesConfig = new Config(); } finally { if (idx > 0) rootTree.next(idx); } } finally { configWalk.release(); } } return this; }
Source:
<code><START> public byte[] decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { <END> return withContext(context -> client.decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)).block(); }</code><technical_language>byte[] [](start = 11, length = 6) updating methods return a data structure a simple type for forwards compat. This return DecryptResult property plaintext</technical_language>

Target:
public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, Context.NONE); }
Source:
<code>private static String getRegion(final String brokerURI) { <START> Pattern pattern = Pattern.compile("iot.(.*).amazonaws.com"); <END> Matcher matcher = pattern.matcher(brokerURI); return matcher.find() ? matcher.group(1) : ""; }</code><technical_language>final</technical_language>

Target:
private static String getRegion(final String brokerURI) { final Pattern pattern = Pattern.compile("iot.(.*).amazonaws.com"); final Matcher matcher = pattern.matcher(brokerURI); return matcher.find() ? matcher.group(1) : ""; }
Source:
<code>private static boolean hasCatalogRegistration(RegistryModule module) { for (Field field : module.getClass().getDeclaredFields()) { RegisterCatalog annotation = field.getAnnotation(RegisterCatalog.class); if (annotation != null) { return true; } } if (module instanceof AlternateCatalogRegistryModule) { try { final Type type = module.getClass().getGenericSuperclass(); Class<?> catalogClass = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0]; <START> CatalogedBy catalogedBy = catalogClass.getAnnotation(CatalogedBy.class); <END> if (catalogedBy != null) { Class<?>[] catalogedBys = catalogedBy.value(); if (catalogedBys.length > 0) { return true; } } } catch (Exception e) { } } return false; }</code><technical_language>is this doing? checking for CatalogedBy annotation</technical_language>

Target:
private static boolean hasCatalogRegistration(RegistryModule module) { for (Field field : module.getClass().getDeclaredFields()) { RegisterCatalog annotation = field.getAnnotation(RegisterCatalog.class); if (annotation != null) { return true; } } if (module instanceof AlternateCatalogRegistryModule) { try { final Type type = module.getClass().getGenericSuperclass(); Class<?> catalogClass = (Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0]; CatalogedBy catalogedBy = catalogClass.getAnnotation(CatalogedBy.class); if (catalogedBy != null) { Class<?>[] catalogedBys = catalogedBy.value(); if (catalogedBys.length > 0) { return true; } } } catch (Exception e) { throw new RuntimeException("Error trying to check for catalog registrations in module: " + module.getClass().getCanonicalName(), e); } } return false; }
Source:
<code>public SpiderAPI(ExtensionSpider extension) { this.extension = extension; this.addApiAction(new ApiAction(ACTION_START_SCAN, new String[] { PARAM_URL }, new String[] { PARAM_MAX_CHILDREN, PARAM_RECURSE })); this.addApiAction(new ApiAction(ACTION_START_SCAN_AS_USER, <START> new String[] { PARAM_URL, PARAM_CONTEXT_ID, PARAM_USER_ID, PARAM_MAX_CHILDREN, PARAM_RECURSE })); <END> this.addApiAction(new ApiAction(ACTION_PAUSE_SCAN, new String[] { PARAM_SCAN_ID })); this.addApiAction(new ApiAction(ACTION_RESUME_SCAN, new String[] { PARAM_SCAN_ID })); this.addApiAction(new ApiAction(ACTION_STOP_SCAN, null, new String[] { PARAM_SCAN_ID })); this.addApiAction(new ApiAction(ACTION_REMOVE_SCAN, new String[] { PARAM_SCAN_ID })); this.addApiAction(new ApiAction(ACTION_PAUSE_ALL_SCANS)); this.addApiAction(new ApiAction(ACTION_RESUME_ALL_SCANS)); this.addApiAction(new ApiAction(ACTION_STOP_ALL_SCANS)); this.addApiAction(new ApiAction(ACTION_REMOVE_ALL_SCANS)); this.addApiAction(new ApiAction(ACTION_CLEAR_EXCLUDED_FROM_SCAN)); this.addApiAction(new ApiAction(ACTION_EXCLUDE_FROM_SCAN, new String[] { PARAM_REGEX })); this.addApiView(new ApiView(VIEW_STATUS, null, new String[] { PARAM_SCAN_ID })); this.addApiView(new ApiView(VIEW_RESULTS, null, new String[] { PARAM_SCAN_ID })); this.addApiView(new ApiView(VIEW_FULL_RESULTS, new String[] { PARAM_SCAN_ID })); this.addApiView(new ApiView(VIEW_SCANS)); this.addApiView(new ApiView(VIEW_EXCLUDED_FROM_SCAN)); }</code><technical_language>_PARAM_RECURSE_ optional (as _PARAM_MAX_CHILDREN_, btw)</technical_language>

Target:
public SpiderAPI(ExtensionSpider extension) { this.extension = extension; this.addApiAction(new ApiAction(ACTION_START_SCAN, new String[] { PARAM_URL }, new String[] { PARAM_MAX_CHILDREN, PARAM_RECURSE })); this.addApiAction(new ApiAction(ACTION_START_SCAN_AS_USER, new String[] { PARAM_URL, PARAM_CONTEXT_ID, PARAM_USER_ID }, new String[] { PARAM_MAX_CHILDREN, PARAM_RECURSE })); this.addApiAction(new ApiAction(ACTION_PAUSE_SCAN, new String[] { PARAM_SCAN_ID })); this.addApiAction(new ApiAction(ACTION_RESUME_SCAN, new String[] { PARAM_SCAN_ID })); this.addApiAction(new ApiAction(ACTION_STOP_SCAN, null, new String[] { PARAM_SCAN_ID })); this.addApiAction(new ApiAction(ACTION_REMOVE_SCAN, new String[] { PARAM_SCAN_ID })); this.addApiAction(new ApiAction(ACTION_PAUSE_ALL_SCANS)); this.addApiAction(new ApiAction(ACTION_RESUME_ALL_SCANS)); this.addApiAction(new ApiAction(ACTION_STOP_ALL_SCANS)); this.addApiAction(new ApiAction(ACTION_REMOVE_ALL_SCANS)); this.addApiAction(new ApiAction(ACTION_CLEAR_EXCLUDED_FROM_SCAN)); this.addApiAction(new ApiAction(ACTION_EXCLUDE_FROM_SCAN, new String[] { PARAM_REGEX })); this.addApiView(new ApiView(VIEW_STATUS, null, new String[] { PARAM_SCAN_ID })); this.addApiView(new ApiView(VIEW_RESULTS, null, new String[] { PARAM_SCAN_ID })); this.addApiView(new ApiView(VIEW_FULL_RESULTS, new String[] { PARAM_SCAN_ID })); this.addApiView(new ApiView(VIEW_SCANS)); this.addApiView(new ApiView(VIEW_EXCLUDED_FROM_SCAN)); }
Source:
<code>public final boolean equals(Object obj) { <START> if (this == obj) return true; <END> if (!(obj instanceof Tuple)) return false; Tuple other = (Tuple) obj; return Arrays.deepEquals(values.toArray(), other.values.toArray()); }</code><technical_language>ok</technical_language>

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Tuple)) return false; Tuple other = (Tuple) obj; return Arrays.deepEquals(values.toArray(), other.values.toArray()); }
Source:
<code><START> private Optional<Entry<String, SamzaResource>> selectStandby(String activeContainerID, <END> String activeContainerResourceID) { log.info("Standby containers for active container {}", this.standbyContainerConstraints.get(activeContainerID), activeContainerID); Optional<StandbyContainerManager.FailoverMetadata> failoverMetadata = activeContainerResourceID == null ? Optional.empty() : this.getFailoverMetadata(activeContainerResourceID); for (String standbyContainerID : this.standbyContainerConstraints.get(activeContainerID)) { if (samzaApplicationState.runningContainers.containsKey(standbyContainerID)) { SamzaResource standbyContainerResource = samzaApplicationState.runningContainers.get(standbyContainerID); if (!failoverMetadata.isPresent() || !failoverMetadata.get() .isStandbyResourceUsed(standbyContainerResource.getResourceID())) { log.info("Returning standby container in running state for active container {}", standbyContainerID, activeContainerID); return Optional.of(new Entry<>(standbyContainerID, standbyContainerResource)); } } } log.info("Did not find any running standby container for active container {}", activeContainerID); return Optional.empty(); }</code><technical_language>Consolidate active-standby lookups a part of FailoverMetadata</technical_language>

Target:
private Optional<Entry<String, SamzaResource>> selectStandby(String activeContainerID, String activeContainerResourceID) { log.info("Standby containers for active container {}", this.standbyContainerConstraints.get(activeContainerID), activeContainerID); Optional<StandbyContainerManager.FailoverMetadata> failoverMetadata = activeContainerResourceID == null ? Optional.empty() : this.getFailoverMetadata(activeContainerResourceID); for (String standbyContainerID : this.standbyContainerConstraints.get(activeContainerID)) { if (samzaApplicationState.runningContainers.containsKey(standbyContainerID)) { SamzaResource standbyContainerResource = samzaApplicationState.runningContainers.get(standbyContainerID); if (!(failoverMetadata.isPresent() && failoverMetadata.get().isStandbyResourceUsed(standbyContainerResource.getResourceID()))) { log.info("Returning standby container in running state for active container {}", standbyContainerID, activeContainerID); return Optional.of(new Entry<>(standbyContainerID, standbyContainerResource)); } } } log.info("Did not find any running standby container for active container {}", activeContainerID); return Optional.empty(); }
Source:
<code>private void connector(IProject prj) { try { IRemoteConnection irc = Util.getRemoteConnection(prj); if(irc == null) return; <START> Activator.log("Connection for project: '" + prj.getName() + "' is '" + irc + "'"); END> Activator.log("Connection address is " + irc.getAddress()); final ITerminalView tvr = (ITerminalView) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage() .showView("org.eclipse.tm.terminal.view.TerminalView"); ITerminalConnector[] itcarray = TerminalConnectorExtension .makeTerminalConnectors(); int remoteTools = -1; for (int i = 0; i < itcarray.length; i++) { if("Remote Tools".equals(itcarray[i].getName()) || "Remote Services".equals(itcarray[i].getName()) || "org.eclipse.ptp.remote.internal.terminal.RemoteToolsConnector".equals(itcarray[i].getId())) { remoteTools = i; break; } } if(itcarray.length==0) { Activator.log("Could not find a terminal connection for "+prj.getName()); return; } if(remoteTools >= 0) { final ITerminalConnector inner = itcarray[remoteTools]; Activator.log("inner="+inner.getId()+","+inner.getName()+","+inner.getSettingsSummary()); ITerminalConnector connector = inner; ISettingsStore store = new HashSettingsStore(); connector.save(store); store.put(RemoteSettings.PROJECT_NAME, prj.getName()); connector.load(store); tvr.newTerminal(connector); } } catch (CoreException e1) { Activator.log(e1); } }</code><technical_language>Logging needs conditional a debug option removed</technical_language>

Target:
private void connector(IProject prj) { try { IRemoteConnection irc = Util.getRemoteConnection(prj); if(irc == null) return; final ITerminalView tvr = (ITerminalView) PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getActivePage() .showView("org.eclipse.tm.terminal.view.TerminalView"); final ITerminalConnector inner = TerminalConnectorExtension.makeTerminalConnector("org.eclipse.ptp.remote.internal.terminal.RemoteToolsConnector"); ITerminalConnector connector = inner; ISettingsStore store = new HashSettingsStore(); connector.save(store); store.put(RemoteSettings.PROJECT_NAME, prj.getName()); connector.load(store); tvr.newTerminal(connector); } catch (CoreException e1) { Activator.log(e1); } }
Source:
<code>private List<SherlockAttribute<?, ?, ?>> sherlockAttributes() { <START> ContentMapping CONTENT_MAPPING = IndexMapping.getContentMapping(); <END> return ImmutableList.<SherlockAttribute<?, ?, ?>>builder() .add(new RangeAttribute<>( SherlockAttributes.YEAR_PARAM, CONTENT_MAPPING.getYear(), IntegerRangeCoercer.create() )) .add(new EnumAttribute<>( SherlockAttributes.TYPE_PARAM, CONTENT_MAPPING.getType(), EnumCoercer.create(ContentType.fromKey()) )) .add(new EnumAttribute<>( SherlockAttributes.PUBLISHER_PARAM, CONTENT_MAPPING.getSource().getKey(), EnumCoercer.create(Sources.fromKey()) )) .add(new SherlockAttribute<Boolean, Instant, DateMapping>( SherlockAttributes.SCHEDULE_UPCOMING_PARAM, CONTENT_MAPPING.getBroadcasts().getTransmissionStartTime(), BooleanCoercer.create() ) { @Override protected NamedParameter<Instant> createParameter( DateMapping mapping, Boolean value ) { if (value) { return RangeParameter.from(mapping, Instant.now()); } else { return RangeParameter.to(mapping, Instant.now()); } } }) .add(new RangeAttribute<>( SherlockAttributes.SCHEDULE_TIME_PARAM, CONTENT_MAPPING.getBroadcasts().getTransmissionStartTime(), InstantRangeCoercer.create() )) .add(new IdAttribute( SherlockAttributes.SCHEDULE_CHANNEL_PARAM, CONTENT_MAPPING.getBroadcasts().getBroadcastOn(), idCodec )) .add(new TermAttribute<>( SherlockAttributes.ON_DEMAND_AVAILABLE_PARAM, CONTENT_MAPPING.getLocations().getAvailable(), BooleanCoercer.create() )) .build(); }</code><technical_language>caps for static values</technical_language>

Target:
private List<SherlockAttribute<?, ?, ?>> sherlockAttributes() { ContentMapping content = IndexMapping.getContentMapping(); return ImmutableList.<SherlockAttribute<?, ?, ?>>builder() .add(new RangeAttribute<>( SherlockParameter.YEAR, content.getYear(), IntegerRangeCoercer.create() )) .add(new EnumAttribute<>( SherlockParameter.TYPE, content.getType(), EnumCoercer.create(ContentType.fromKey()) )) .add(new EnumAttribute<>( SherlockParameter.PUBLISHER, content.getSource().getKey(), EnumCoercer.create(Sources.fromKey()) )) .add(new SherlockAttribute<Boolean, Instant, DateMapping>( SherlockParameter.SCHEDULE_UPCOMING, content.getBroadcasts().getTransmissionStartTime(), BooleanCoercer.create() ) { @Override protected NamedParameter<Instant> createParameter( DateMapping mapping, @Nonnull Boolean value ) { if (value) { return RangeParameter.from(mapping, Instant.now()); } else { return RangeParameter.to(mapping, Instant.now()); } } }) .add(new RangeAttribute<>( SherlockParameter.SCHEDULE_TIME, content.getBroadcasts().getTransmissionStartTime(), InstantRangeCoercer.create() )) .add(new IdAttribute( SherlockParameter.SCHEDULE_CHANNEL, content.getBroadcasts().getBroadcastOn(), idCodec )) .add(new TermAttribute<>( SherlockParameter.ON_DEMAND_AVAILABLE, content.getLocations().getAvailable(), BooleanCoercer.create() )) .build(); }
Source:
<code>public void startFailedAutoStartVms() { LinkedList<Pair<Guid, DateTime>> idsToRemove = new LinkedList<>(); final DateTime now = DateTime.getNow(); final DateTime nextTimeOfRetryToRun = now.AddSeconds(RETRY_TO_RUN_HA_VM_INTERVAL); for(Pair<Guid, DateTime> vmIdAndDateTime: autoStartVmsToRun) { if (now.compareTo(vmIdAndDateTime.getSecond()) < 0) { continue; } Guid vmId = vmIdAndDateTime.getFirst(); EngineLock runVmLock = createLockForRunVmCommand(vmId); if (!getLockManager().acquireLock(runVmLock).getFirst()) { <START> log.infoFormat("Could not acquire lock for running HA VM {0}", vmId); <END> continue; } if (!runVm(vmId, runVmLock) && getVmDynamicDao().get(vmId).getStatus() == VMStatus.Down) { AuditLogableBase event = new AuditLogableBase(); event.setVmId(vmId); AuditLogDirector.log(event, AuditLogType.HA_VM_RESTART_FAILED); vmIdAndDateTime.setSecond(nextTimeOfRetryToRun); continue; } idsToRemove.add(vmIdAndDateTime); } autoStartVmsToRun.removeAll(idsToRemove); }</code><technical_language>iirc, this written (~)every log while vm is locked, this is much.. move debug</technical_language>

Target:
public void startFailedAutoStartVms() { LinkedList<Pair<Guid, DateTime>> idsToRemove = new LinkedList<>(); final DateTime now = DateTime.getNow(); final DateTime nextTimeOfRetryToRun = now.AddSeconds(RETRY_TO_RUN_HA_VM_INTERVAL); for(Pair<Guid, DateTime> vmIdAndDateTime: autoStartVmsToRun) { if (now.compareTo(vmIdAndDateTime.getSecond()) < 0) { continue; } Guid vmId = vmIdAndDateTime.getFirst(); EngineLock runVmLock = createEngineLockForRunVm(vmId, getLockMessage()); if (!getLockManager().acquireLock(runVmLock).getFirst()) { log.debugFormat("Could not acquire lock for running HA VM {0}", vmId); continue; } if (!runVm(vmId, runVmLock) && getVmDynamicDao().get(vmId).getStatus() == VMStatus.Down) { AuditLogableBase event = new AuditLogableBase(); event.setVmId(vmId); AuditLogDirector.log(event, AuditLogType.HA_VM_RESTART_FAILED); vmIdAndDateTime.setSecond(nextTimeOfRetryToRun); continue; } idsToRemove.add(vmIdAndDateTime); } autoStartVmsToRun.removeAll(idsToRemove); }
Source:
<code>private Collection<Item> getItemsFromModel(String modelName) { logger.debug("Read items from model '{}'", modelName); List<Item> items = new ArrayList<Item>(); if (modelRepository != null) { ItemModel model = (ItemModel) modelRepository.getModel(modelName); if (model != null) { for (ModelItem modelItem : model.getItems()) { Item item = createItemFromModelItem(modelItem); if (item != null) { for (String groupName : modelItem.getGroups()) { ((GenericItem) item).addGroupName(groupName); } items.add(item); } } } } <START> itemsMap.put(modelName, items); <END> return items; }</code><technical_language>This a brute force fix me. Note itemsMap is filled in modelChanged, times. place getAll() method this is called (once) added events received? if this additionally check, entry in map exists, nicer</technical_language>

Target:
private Collection<Item> getItemsFromModel(String modelName) { logger.debug("Read items from model '{}'", modelName); List<Item> items = new ArrayList<Item>(); if (modelRepository != null) { ItemModel model = (ItemModel) modelRepository.getModel(modelName); if (model != null) { for (ModelItem modelItem : model.getItems()) { Item item = createItemFromModelItem(modelItem); if (item != null) { for (String groupName : modelItem.getGroups()) { ((GenericItem) item).addGroupName(groupName); } items.add(item); } } } } return items; }
Source:
<code>public final boolean equals(Object o) { if (this == o) { return true; } if (o == null || !(o instanceof SerializerConfig)) { return false; } SerializerConfig that = (SerializerConfig) o; <START> return Objects.equals(implementationNameInternal(), that.implementationNameInternal()) <END> && Objects.equals(typeClassNameInternal(), that.typeClassNameInternal()); }</code><technical_language>internal methods in use</technical_language>

Target:
public final boolean equals(Object o) { if (this == o) { return true; } if (o == null || !(o instanceof SerializerConfig)) { return false; } SerializerConfig that = (SerializerConfig) o; return Objects.equals(implementation, that.implementation) && Objects.equals(className, that.className) && Objects.equals(typeClass, that.typeClass) && Objects.equals(typeClassName, that.typeClassName); }
Source:
<code>private void parseDelete(final ReceiveCommand cmd) { RefControl ctl = projectControl.controlForRef(cmd.getRefName()); <START> String refName = cmd.getRefName(); <END> if (refName.startsWith("refs/changes/")) { errors.put(Error.DELETE_CHANGES, refName); reject(cmd, "cannot delete changes"); } else if (ctl.canDelete()) { batch.addCommand(cmd); } else { if (GitRepositoryManager.REF_CONFIG.equals(ctl.getRefName())) { reject(cmd, "cannot delete project configuration"); } else { errors.put(Error.DELETE, ctl.getRefName()); reject(cmd, "cannot delete references"); } } }</code><technical_language>Remove this variable ctl.getRefName() rest of this method is doing</technical_language>

Target:
private void parseDelete(final ReceiveCommand cmd) { RefControl ctl = projectControl.controlForRef(cmd.getRefName()); String refName = ctl.getRefName(); if (refName.startsWith("refs/changes/")) { errors.put(Error.DELETE_CHANGES, refName); reject(cmd, "cannot delete changes"); } else if (ctl.canDelete()) { batch.addCommand(cmd); } else { if (GitRepositoryManager.REF_CONFIG.equals(refName)) { reject(cmd, "cannot delete project configuration"); } else { errors.put(Error.DELETE, ctl.getRefName()); reject(cmd, "cannot delete references"); } } }
Source:
<code>static long gdk_pixbuf_new_from_file(String filename) { int length = filename.length (); char chars = new char [length]; filename.getChars (0, length, chars, 0); byte buffer = Converter.wcsToMbcs(chars, true); <START> long pixbuf = GDK.gdk_pixbuf_new_from_file(buffer, null); return pixbuf; <END> }</code><technical_language>This combined line</technical_language>

Target:
static long gdk_pixbuf_new_from_file(String filename) { int length = filename.length (); char chars = new char [length]; filename.getChars (0, length, chars, 0); byte buffer = Converter.wcsToMbcs(chars, true); return GDK.gdk_pixbuf_new_from_file(buffer, null); }
Source:
<code>public void loadLoanAccountTemplate(int clientId, int productId) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscriptions.add(mDataManagerLoan.getLoansAccountTemplate(clientId, productId) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<LoanTemplate>() { @Override public void onCompleted() { getMvpView().showProgressbar(false); } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showFetchingError("Failed to load AccountTemplate"); } @Override public void onNext(LoanTemplate loanTemplate) { getMvpView().showProgressbar(false); getMvpView().showLoanAccountTemplate(loanTemplate); <START> getMvpView().setDefaultValues( <END> loanTemplate.getInterestRateFrequencyType().getValue()); } })); }</code><technical_language>do call this method here, Call in method showLoanAccountTemplate() in Fragment</technical_language>

Target:
public void loadLoanAccountTemplate(int clientId, int productId) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscriptions.add(mDataManagerLoan.getLoansAccountTemplate(clientId, productId) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<LoanTemplate>() { @Override public void onCompleted() { getMvpView().showProgressbar(false); } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showFetchingError("Failed to load AccountTemplate"); } @Override public void onNext(LoanTemplate loanTemplate) { getMvpView().showProgressbar(false); getMvpView().showLoanAccountTemplate(loanTemplate); } })); }
Source:
<code>public void shouldReturnCorporateSurchargeAndTotalAmount_V1() { long chargeId = nextInt(); String externalChargeId = "charge1"; app.getDatabaseTestHelper().addCharge(chargeId, externalChargeId, accountId, AMOUNT, AUTHORISATION_SUCCESS, returnUrl, null, ServicePaymentReference.of("ref"), null, email); app.getDatabaseTestHelper().updateChargeCardDetails(chargeId, "unknown-brand", "1234", "123456", "Mr. McPayment", "03/18", "line1", null, "postcode", "city", null, "country"); app.getDatabaseTestHelper().updateCorporateSurcharge(chargeId, 50L); app.getDatabaseTestHelper().addToken(chargeId, "tokenId"); getChargeApi .withAccountId(accountId) .getCharges() .statusCode(OK.getStatusCode()) .contentType(JSON) .body("results[0]." + JSON_CHARGE_KEY, is(externalChargeId)) .body("results[0]." + JSON_CORPORATE_SURCHARGE_KEY, is(50)) .body("results[0]." + JSON_TOTAL_AMOUNT_KEY, is(AMOUNT.intValue() + 50)); <START> } <END></code><technical_language>Do need versions of this test check other endpoints in ChargesApiResource class (for is a plethora)</technical_language>

Target:
public void shouldReturnCorporateSurchargeAndTotalAmount_V1() { long chargeId = nextInt(); String externalChargeId = "charge1"; app.getDatabaseTestHelper().addCharge(chargeId, externalChargeId, accountId, AMOUNT, AUTHORISATION_SUCCESS, returnUrl, null, ServicePaymentReference.of("ref"), null, email); app.getDatabaseTestHelper().updateChargeCardDetails(chargeId, "unknown-brand", "1234", "123456", "Mr. McPayment", "03/18", "line1", null, "postcode", "city", null, "country"); app.getDatabaseTestHelper().updateCorporateSurcharge(chargeId, 50L); app.getDatabaseTestHelper().addToken(chargeId, "tokenId"); getChargeApi .withAccountId(accountId) .getTransactions() .statusCode(OK.getStatusCode()) .contentType(JSON) .body("results[0]." + JSON_CHARGE_KEY, is(externalChargeId)) .body("results[0]." + JSON_CORPORATE_SURCHARGE_KEY, is(50)) .body("results[0]." + JSON_TOTAL_AMOUNT_KEY, is(AMOUNT.intValue() + 50)); }